diff --git a/deploy/packaging/debian/rfxdevices.noarch b/deploy/packaging/debian/rfxdevices.noarch index 26befa1031..d34ed467e0 100644 --- a/deploy/packaging/debian/rfxdevices.noarch +++ b/deploy/packaging/debian/rfxdevices.noarch @@ -3,6 +3,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/BASLERACA.py ./usr/local/mdsplus/pydevices/RfxDevices/BCM2835_ADC.py ./usr/local/mdsplus/pydevices/RfxDevices/BCM2835_DAC.py +./usr/local/mdsplus/pydevices/RfxDevices/BCM_CONFIG.py ./usr/local/mdsplus/pydevices/RfxDevices/CAENDT5720.py ./usr/local/mdsplus/pydevices/RfxDevices/CAENDT5724.py ./usr/local/mdsplus/pydevices/RfxDevices/CAENV1740.py @@ -91,6 +92,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_MHD_CTRL.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_MHD_I.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_NE.py +./usr/local/mdsplus/pydevices/RfxDevices/MARTE_RF_CTRL.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_RTSM.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_WAVEGEN.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_XRAY.py @@ -110,6 +112,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/PI_SCT320.py ./usr/local/mdsplus/pydevices/RfxDevices/PLFE.py ./usr/local/mdsplus/pydevices/RfxDevices/PTGREY.py +./usr/local/mdsplus/pydevices/RfxDevices/PV2MDSEVENT.py ./usr/local/mdsplus/pydevices/RfxDevices/PV_WAVE_SETUP.py ./usr/local/mdsplus/pydevices/RfxDevices/REDPYTADC.py ./usr/local/mdsplus/pydevices/RfxDevices/RFXVICONTROL.py @@ -117,6 +120,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/RFX_PROTECTIONS.py ./usr/local/mdsplus/pydevices/RfxDevices/RFX_RPADC.py ./usr/local/mdsplus/pydevices/RfxDevices/RFX_RPDAC.py +./usr/local/mdsplus/pydevices/RfxDevices/RGA.py ./usr/local/mdsplus/pydevices/RfxDevices/SIG_SNAPSHOT.py ./usr/local/mdsplus/pydevices/RfxDevices/SIS3820.py ./usr/local/mdsplus/pydevices/RfxDevices/SOFT_TRIGGER.py @@ -126,6 +130,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/SPIDER_PARAMS.py ./usr/local/mdsplus/pydevices/RfxDevices/SPIDER_SETUP.py ./usr/local/mdsplus/pydevices/RfxDevices/SPIDER_SM.py +./usr/local/mdsplus/pydevices/RfxDevices/STK_TEMP.py ./usr/local/mdsplus/pydevices/RfxDevices/STREAM_SETUP.py ./usr/local/mdsplus/pydevices/RfxDevices/ZELOS2150GV.py ./usr/local/mdsplus/pydevices/RfxDevices/__init__.py @@ -805,6 +810,7 @@ ./usr/local/mdsplus/tdi/RfxDevices/getBradErrorSignal.fun ./usr/local/mdsplus/tdi/RfxDevices/getBradErrorSignalName.fun ./usr/local/mdsplus/tdi/RfxDevices/getMembersName.fun +./usr/local/mdsplus/tdi/RfxDevices/getSpiderGasType.fun ./usr/local/mdsplus/tdi/RfxDevices/getSpiderShotTime.fun ./usr/local/mdsplus/tdi/RfxDevices/getSpiderStateTime.fun ./usr/local/mdsplus/tdi/RfxDevices/getVersions.fun @@ -845,6 +851,7 @@ ./usr/local/mdsplus/tdi/RfxDevices/sigBit.fun ./usr/local/mdsplus/tdi/RfxDevices/sigMean.fun ./usr/local/mdsplus/tdi/RfxDevices/sigSlopeTimes.py +./usr/local/mdsplus/tdi/RfxDevices/spiderBlipNumFromTime.py ./usr/local/mdsplus/tdi/RfxDevices/spiderBurstClock.fun ./usr/local/mdsplus/tdi/RfxDevices/spiderClockSegment.fun ./usr/local/mdsplus/tdi/RfxDevices/spider_finish_pulse.fun diff --git a/deploy/packaging/redhat/rfxdevices.noarch b/deploy/packaging/redhat/rfxdevices.noarch index f172750fe6..86cf20bab8 100644 --- a/deploy/packaging/redhat/rfxdevices.noarch +++ b/deploy/packaging/redhat/rfxdevices.noarch @@ -4,6 +4,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/BASLERACA.py ./usr/local/mdsplus/pydevices/RfxDevices/BCM2835_ADC.py ./usr/local/mdsplus/pydevices/RfxDevices/BCM2835_DAC.py +./usr/local/mdsplus/pydevices/RfxDevices/BCM_CONFIG.py ./usr/local/mdsplus/pydevices/RfxDevices/CAENDT5720.py ./usr/local/mdsplus/pydevices/RfxDevices/CAENDT5724.py ./usr/local/mdsplus/pydevices/RfxDevices/CAENV1740.py @@ -92,6 +93,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_MHD_CTRL.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_MHD_I.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_NE.py +./usr/local/mdsplus/pydevices/RfxDevices/MARTE_RF_CTRL.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_RTSM.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_WAVEGEN.py ./usr/local/mdsplus/pydevices/RfxDevices/MARTE_XRAY.py @@ -111,6 +113,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/PI_SCT320.py ./usr/local/mdsplus/pydevices/RfxDevices/PLFE.py ./usr/local/mdsplus/pydevices/RfxDevices/PTGREY.py +./usr/local/mdsplus/pydevices/RfxDevices/PV2MDSEVENT.py ./usr/local/mdsplus/pydevices/RfxDevices/PV_WAVE_SETUP.py ./usr/local/mdsplus/pydevices/RfxDevices/REDPYTADC.py ./usr/local/mdsplus/pydevices/RfxDevices/RFXVICONTROL.py @@ -118,6 +121,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/RFX_PROTECTIONS.py ./usr/local/mdsplus/pydevices/RfxDevices/RFX_RPADC.py ./usr/local/mdsplus/pydevices/RfxDevices/RFX_RPDAC.py +./usr/local/mdsplus/pydevices/RfxDevices/RGA.py ./usr/local/mdsplus/pydevices/RfxDevices/SIG_SNAPSHOT.py ./usr/local/mdsplus/pydevices/RfxDevices/SIS3820.py ./usr/local/mdsplus/pydevices/RfxDevices/SOFT_TRIGGER.py @@ -127,6 +131,7 @@ ./usr/local/mdsplus/pydevices/RfxDevices/SPIDER_PARAMS.py ./usr/local/mdsplus/pydevices/RfxDevices/SPIDER_SETUP.py ./usr/local/mdsplus/pydevices/RfxDevices/SPIDER_SM.py +./usr/local/mdsplus/pydevices/RfxDevices/STK_TEMP.py ./usr/local/mdsplus/pydevices/RfxDevices/STREAM_SETUP.py ./usr/local/mdsplus/pydevices/RfxDevices/ZELOS2150GV.py ./usr/local/mdsplus/pydevices/RfxDevices/__init__.py @@ -807,6 +812,7 @@ ./usr/local/mdsplus/tdi/RfxDevices/getBradErrorSignal.fun ./usr/local/mdsplus/tdi/RfxDevices/getBradErrorSignalName.fun ./usr/local/mdsplus/tdi/RfxDevices/getMembersName.fun +./usr/local/mdsplus/tdi/RfxDevices/getSpiderGasType.fun ./usr/local/mdsplus/tdi/RfxDevices/getSpiderShotTime.fun ./usr/local/mdsplus/tdi/RfxDevices/getSpiderStateTime.fun ./usr/local/mdsplus/tdi/RfxDevices/getVersions.fun @@ -847,6 +853,7 @@ ./usr/local/mdsplus/tdi/RfxDevices/sigBit.fun ./usr/local/mdsplus/tdi/RfxDevices/sigMean.fun ./usr/local/mdsplus/tdi/RfxDevices/sigSlopeTimes.py +./usr/local/mdsplus/tdi/RfxDevices/spiderBlipNumFromTime.py ./usr/local/mdsplus/tdi/RfxDevices/spiderBurstClock.fun ./usr/local/mdsplus/tdi/RfxDevices/spiderClockSegment.fun ./usr/local/mdsplus/tdi/RfxDevices/spider_finish_pulse.fun diff --git a/device_support/basler/BASLERACA.cpp b/device_support/basler/BASLERACA.cpp index f52f0e82a1..69dff88069 100644 --- a/device_support/basler/BASLERACA.cpp +++ b/device_support/basler/BASLERACA.cpp @@ -40,473 +40,493 @@ using namespace std; #include #include -#define BUFFER_COUNT 16 +#define BUFFER_COUNT 16 #define ERROR -1 #define SUCCESS 0 -// if defined, print to stdout messages. +//if defined, print to stdout messages. #define debug + #define MAX_CAM 10 static BASLER_ACA *camPtr[MAX_CAM] = {0}; static char errorOnOpen[512]; -#ifdef __cplusplus -extern "C" + +#ifdef __cplusplus +extern "C" +{ +#endif + + +int baslerOpen(const char *ipAddress, int *camHandle) { -#endif + BASLER_ACA *cam; + int cameraHandle; + + errorOnOpen[0] = 0; + + cam = new BASLER_ACA(ipAddress); + + if(cam->checkLastOp()==ERROR) + { + cam->getLastError(errorOnOpen); + delete(cam); + return ERROR; + } + + for( cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle] ; cameraHandle++); + + if( cameraHandle < MAX_CAM ) + { + camPtr[cameraHandle] = cam; + *camHandle = cameraHandle; + return SUCCESS; + } + else + { + sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); + *camHandle = -1; + return ERROR; + } +} - int baslerOpen(const char *ipAddress, int *camHandle) - { - BASLER_ACA *cam; - int cameraHandle; - errorOnOpen[0] = 0; +int baslerIsConnected( int camHandle ) +{ + if( camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0 ) + { + sprintf(errorOnOpen, "Camera does not connect"); + return ERROR; + } + return SUCCESS; +} - cam = new BASLER_ACA(ipAddress); +int baslerClose(int camHandle) +{ + delete(camPtr[camHandle]); + camPtr[camHandle] = 0; + + return SUCCESS; +} - if (cam->checkLastOp() == ERROR) - { - cam->getLastError(errorOnOpen); - delete (cam); - return ERROR; - } - for (cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle]; - cameraHandle++) - ; +int checkLastOp(int camHandle) +{ + return camPtr[camHandle]->checkLastOp(); +} - if (cameraHandle < MAX_CAM) - { - camPtr[cameraHandle] = cam; - *camHandle = cameraHandle; - return SUCCESS; - } - else - { - sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); - *camHandle = -1; - return ERROR; - } - } +int readInternalTemperature(int camHandle) +{ + return camPtr[camHandle]->readInternalTemperature(); +} - int baslerIsConnected(int camHandle) - { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) - { - sprintf(errorOnOpen, "Camera does not connect"); - return ERROR; - } - return SUCCESS; - } +int setExposure(int camHandle, double exposure) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setExposure(exposure); + return ERROR; +} - int baslerClose(int camHandle) - { - delete (camPtr[camHandle]); - camPtr[camHandle] = 0; - return SUCCESS; - } +int setExposureAuto(int camHandle, char *exposureAuto) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setExposureAuto(exposureAuto); + return ERROR; +} - int checkLastOp(int camHandle) { return camPtr[camHandle]->checkLastOp(); } - int readInternalTemperature(int camHandle) - { - return camPtr[camHandle]->readInternalTemperature(); - } +int setGain(int camHandle, int gain) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setGain(gain); + return ERROR; +} - int setExposure(int camHandle, double exposure) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setExposure(exposure); - return ERROR; - } - int setExposureAuto(int camHandle, char *exposureAuto) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setExposureAuto(exposureAuto); - return ERROR; - } +int setGainAuto(int camHandle, char *gainAuto) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setGainAuto(gainAuto); + return ERROR; +} - int setGain(int camHandle, int gain) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setGain(gain); - return ERROR; - } - int setGainAuto(int camHandle, char *gainAuto) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setGainAuto(gainAuto); - return ERROR; - } +int setGammaEnable(int camHandle, char *gammaEnable) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setGammaEnable(gammaEnable); + return ERROR; +} - int setGammaEnable(int camHandle, char *gammaEnable) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setGammaEnable(gammaEnable); - return ERROR; - } - int setFrameRate(int camHandle, double frameRate) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setFrameRate(frameRate); - return ERROR; - } +int setFrameRate(int camHandle, double frameRate) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setFrameRate(frameRate); + return ERROR; +} - int setReadoutArea(int camHandle, int x, int y, int width, int height) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setReadoutArea(x, y, width, height); - return ERROR; - } - int setPixelFormat(int camHandle, char *pixelFormat) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setPixelFormat(pixelFormat); - return ERROR; - } +int setReadoutArea(int camHandle, int x, int y, int width, int height) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setReadoutArea(x, y, width, height); + return ERROR; +} - int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startAcquisition(width, height, payloadSize); - return ERROR; - } - int stopAcquisition(int camHandle) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopAcquisition(); - return ERROR; - } +int setPixelFormat(int camHandle, char *pixelFormat) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setPixelFormat(pixelFormat); + return ERROR; +} - int getFrame(int camHandle, int *status, void *frame, void *metaData) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->getFrame(status, frame, metaData); - return ERROR; - } - int setAcquisitionMode(int camHandle, int storeEnabled, - int acqSkipFrameNumber) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setAcquisitionMode(storeEnabled, - acqSkipFrameNumber); - return ERROR; - } +int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->startAcquisition(width, height, payloadSize); + return ERROR; +} - int setTriggerMode(int camHandle, int triggerMode, double burstDuration, - int numTrigger) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTriggerMode(triggerMode, burstDuration, - numTrigger); - return ERROR; - } - int softwareTrigger(int camHandle) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->softwareTrigger(); - return ERROR; - } +int stopAcquisition(int camHandle) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->stopAcquisition(); + return ERROR; +} - int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTreeInfo(treePtr, framesNid, timebaseNid, - framesMetadNid, frame0TimeNid); - return ERROR; - } - int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, - const char *streamingServer, int streamingPort, int lowLim, - int highLim, int adjRoiX, int adjRoiY, int adjRoiW, - int adjRoiH, const char *deviceName) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setStreamingMode( - streamingEnabled, autoAdjustLimit, streamingServer, streamingPort, - lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); - return ERROR; - } +int getFrame(int camHandle, int *status, void *frame, void *metaData) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->getFrame(status, frame, metaData); + return ERROR; +} - int startFramesAcquisition(int camHandle) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startFramesAcquisition(); - return ERROR; - } +int setAcquisitionMode( int camHandle, int storeEnabled, int acqSkipFrameNumber) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setAcquisitionMode( storeEnabled, acqSkipFrameNumber); + return ERROR; +} - int stopFramesAcquisition(int camHandle) - { - if (baslerIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopFramesAcquisition(); - return ERROR; - } +int setTriggerMode( int camHandle, int triggerMode, double burstDuration, int numTrigger ) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setTriggerMode( triggerMode, burstDuration, numTrigger ); + return ERROR; +} - void getLastError(int camHandle, char *msg) - { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) - { - sprintf(msg, "%s", (errorOnOpen[0] == 0) ? "" : errorOnOpen); - return; - } - camPtr[camHandle]->getLastError(msg); - } +int softwareTrigger(int camHandle) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->softwareTrigger(); + return ERROR; +} -#ifdef __cplusplus +int setTreeInfo( int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) +{ + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setTreeInfo( treePtr, framesNid, timebaseNid, framesMetadNid, frame0TimeNid ); + return ERROR; } -#endif -BASLER_ACA::BASLER_ACA(const char *ipAddress) +int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, + const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) { - try - { - memset(error, 0, sizeof(error)); - memcpy(this->ipAddress, ipAddress, strlen(ipAddress) + 1); - this->pCamera = NULL; + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setStreamingMode( streamingEnabled, autoAdjustLimit, streamingServer, streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); + return ERROR; - printf("\n Init COUNT = %d %d\n", this->getCount()); - if (this->getCount() == 1) - { - printf("\n\n%s:Pylon Inizialize.\n\n", this->ipAddress); - PylonInitialize(); - } - CTlFactory &TlFactory = CTlFactory::GetInstance(); - CBaslerGigEDeviceInfo di; - di.SetIpAddress(ipAddress); - this->pDevice = TlFactory.CreateDevice(di); - // old this->pCamera = new - // Pylon::CBaslerGigEInstantCamera::CBaslerGigEInstantCamera(this->pDevice); - this->pCamera = new CBaslerGigEInstantCamera(this->pDevice); - pCamera->Open(); - printf("%s: Device Connected.\n", this->ipAddress); - lastOpRes = SUCCESS; - } - catch (const GenericException &e) - { - cerr << this->ipAddress - << ": Error Device connection. Reason: " << e.GetDescription() << endl; - lastOpRes = ERROR; - } } -BASLER_ACA::BASLER_ACA() // new 25/07/2013: let to use the device without the - // camera +int startFramesAcquisition(int camHandle) { - // this->lDevice = new PvDevice(); //SDK 3 - // SDK 4 09/03/2016 NON sembra possibile creare un PVDEVICE se non ho la - // telecamera + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->startFramesAcquisition(); + return ERROR; } -BASLER_ACA::~BASLER_ACA() +int stopFramesAcquisition(int camHandle) { - printf("COUNT = %d %d\n", this->getCount(), pCamera); - /* - if ( pCamera != NULL && pCamera->IsOpen() ) - pCamera->Close(); - */ - if (this->getCount() == 1) - { - printf("PylonTerminate.\n"); - PylonTerminate(); - } - printf("%s: Device Disconnected.\n", this->ipAddress); + if( baslerIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->stopFramesAcquisition(); + return ERROR; } -int BASLER_ACA::checkLastOp() +void getLastError(int camHandle, char *msg) { - /* - printf("Info %d (%s)\n", this->lResult.IsOK(), - lResult.GetDescription().GetAscii() ); if ( !this->lResult.IsOK() ) - printLastError("(%s)\n", lResult.GetDescription().GetAscii() - ); - */ - return lastOpRes; + if( camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0 ) + { + sprintf(msg, "%s", (errorOnOpen[0]==0) ? "" : errorOnOpen); + return; + } + camPtr[camHandle]->getLastError(msg); } -int BASLER_ACA::readInternalTemperature() + + +#ifdef __cplusplus +} +#endif + + + + +BASLER_ACA::BASLER_ACA(const char *ipAddress) +{ + try + { + memset(error, 0, sizeof(error)); + memcpy(this->ipAddress, ipAddress, strlen(ipAddress)+1); + this->pCamera = NULL; + this->trigEvent = NULL; + + //printf("\n Init COUNT = %d %d\n", this->getCount()); + if( this->getCount() == 1) + { + printf("\n\n%s:Pylon Inizialize.\n\n",this->ipAddress); + PylonInitialize(); + } + CTlFactory& TlFactory = CTlFactory::GetInstance(); + CBaslerGigEDeviceInfo di; + di.SetIpAddress(ipAddress); + this->pDevice = TlFactory.CreateDevice( di); + // old this->pCamera = new Pylon::CBaslerGigEInstantCamera::CBaslerGigEInstantCamera(this->pDevice); + this->pCamera = new CBaslerGigEInstantCamera(this->pDevice); + pCamera->Open(); + printf("%s: Device Connected.\n", this->ipAddress); + lastOpRes=SUCCESS; + + printf("EVENTO abilitato \n"); + //CT MDSplus acquisition Triggered on MDSevent + eventTrigger = 0; + trigEvent = new TriggerMdsEvent("__CCD_TRIGGER__", this); + trigEvent->start(); + + } + catch (const GenericException & e) + { + cerr << this->ipAddress << ": Error Device connection. Reason: " << e.GetDescription() << endl; + lastOpRes=ERROR; + } +} + + +BASLER_ACA::BASLER_ACA() //new 25/07/2013: let to use the device without the camera { - // Select the kind of internal temperature as the device temperature - pCamera->TemperatureSelector.SetValue(TemperatureSelector_Coreboard); - // Read the device temperature - double t = pCamera->TemperatureAbs.GetValue(); - printf("%s: Camera Temperature is now %3.2f°C\n", this->ipAddress, t); - this->internalTemperature = t; + //this->lDevice = new PvDevice(); //SDK 3 + //SDK 4 09/03/2016 NON sembra possibile creare un PVDEVICE se non ho la telecamera +} - return SUCCESS; + +BASLER_ACA::~BASLER_ACA() +{ +// printf("COUNT = %d %d\n", this->getCount(), pCamera); +/* + if ( pCamera != NULL && pCamera->IsOpen() ) + pCamera->Close(); +*/ + if( this->getCount() == 1) + { + printf("PylonTerminate.\n"); + PylonTerminate(); + } + printf("%s: Device Disconnected.\n", this->ipAddress); + + if(this->trigEvent != NULL) + delete trigEvent; } -int BASLER_ACA::setExposure(double exposure) + + + +int BASLER_ACA::checkLastOp() { - if (IsWritable(pCamera->ExposureTimeAbs)) - { - pCamera->ExposureTimeAbs.SetValue(exposure); - // pCamera->ExposureTimeRaw.SetValue(exposure); //not to use! - cout << this->ipAddress << ": Exposure set to: " << exposure << endl; - } - this->exposure = exposure; +/* + printf("Info %d (%s)\n", this->lResult.IsOK(), lResult.GetDescription().GetAscii() ); + if ( !this->lResult.IsOK() ) + printLastError("(%s)\n", lResult.GetDescription().GetAscii() ); +*/ + return lastOpRes; +} - return SUCCESS; + +int BASLER_ACA::readInternalTemperature() +{ + // Select the kind of internal temperature as the device temperature + pCamera->TemperatureSelector.SetValue(TemperatureSelector_Coreboard); + // Read the device temperature + double t = pCamera->TemperatureAbs.GetValue(); + printf("%s: Camera Temperature is now %3.2f°C\n", this->ipAddress, t); + this->internalTemperature=t; + + return SUCCESS; } + + +int BASLER_ACA::setExposure(double exposure) +{ + if (IsWritable(pCamera->ExposureTimeAbs)) + { + pCamera->ExposureTimeAbs.SetValue(exposure); + //pCamera->ExposureTimeRaw.SetValue(exposure); //not to use! + cout << this->ipAddress << ": Exposure set to: " << exposure << endl; + } + this->exposure=exposure; + + return SUCCESS; +} + + + int BASLER_ACA::setExposureAuto(char *exposureAuto) -{ - INodeMap &nodeMap = pCamera->GetNodeMap(); +{ + INodeMap& nodeMap = pCamera->GetNodeMap(); CEnumerationPtr pFormat(nodeMap.GetNode("ExposureAuto")); - if (IsAvailable(pFormat->GetEntryByName(exposureAuto))) // OFF Once Continuous + if(IsAvailable( pFormat->GetEntryByName(exposureAuto))) //OFF Once Continuous { - pFormat->FromString(exposureAuto); - cout << this->ipAddress - << ": Exposure Auto set to : " << pFormat->ToString() << endl; + pFormat->FromString(exposureAuto); + cout << this->ipAddress << ": Exposure Auto set to : " << pFormat->ToString() << endl; } - + return SUCCESS; } + int BASLER_ACA::setGainAuto(char *gainAuto) { - INodeMap &nodeMap = pCamera->GetNodeMap(); + INodeMap& nodeMap = pCamera->GetNodeMap(); CEnumerationPtr pFormat(nodeMap.GetNode("GainAuto")); - if (IsAvailable(pFormat->GetEntryByName(gainAuto))) // OFF Once Continuous + if(IsAvailable( pFormat->GetEntryByName(gainAuto))) //OFF Once Continuous { - pFormat->FromString(gainAuto); - cout << this->ipAddress << ": Gain Auto set to : " << pFormat->ToString() - << endl; + pFormat->FromString(gainAuto); + cout << this->ipAddress << ": Gain Auto set to : " << pFormat->ToString() << endl; } - + return SUCCESS; } int BASLER_ACA::setGain(int gain) { - if (IsWritable(pCamera->GainRaw)) - { - pCamera->GainRaw.SetValue(gain); - cout << this->ipAddress << ": Gain set to: " << gain << endl; - } - this->gain = gain; + if (IsWritable(pCamera->GainRaw)) + { + pCamera->GainRaw.SetValue(gain); + cout << this->ipAddress << ": Gain set to: " << gain << endl; + } + this->gain = gain; - return SUCCESS; + return SUCCESS; } int BASLER_ACA::setGammaEnable(char *gammaEnable) { - if (strcmp(gammaEnable, "On") == 0) + if(strcmp(gammaEnable, "On")==0) { pCamera->GammaEnable.SetValue(true); } - if (strcmp(gammaEnable, "Off") == 0) + if(strcmp(gammaEnable, "Off")==0) { pCamera->GammaEnable.SetValue(false); } - - cout << this->ipAddress << ": Gamma Enable set to: " << gammaEnable << endl; + + cout << this->ipAddress << ": Gamma Enable set to: " << gammaEnable << endl; return SUCCESS; } int BASLER_ACA::setFrameRate(double frameRate) { - pCamera->AcquisitionFrameRateEnable.SetValue(true); - pCamera->AcquisitionFrameRateAbs.SetValue(frameRate); - cout << this->ipAddress << ": Frame Rate set to: " << frameRate << endl; - this->frameRate = frameRate; - return SUCCESS; + pCamera->AcquisitionFrameRateEnable.SetValue(true); + pCamera->AcquisitionFrameRateAbs.SetValue(frameRate); + cout << this->ipAddress << ": Frame Rate set to: " << frameRate << endl; + this->frameRate = frameRate; + return SUCCESS; } + int BASLER_ACA::setReadoutArea(int x, int y, int width, int height) { - INodeMap &nodeMap = pCamera->GetNodeMap(); + INodeMap& nodeMap = pCamera->GetNodeMap(); - try - { - CIntegerPtr offsetX(nodeMap.GetNode("OffsetX")); - CIntegerPtr offsetY(nodeMap.GetNode("OffsetY")); - CIntegerPtr widthCI(nodeMap.GetNode("Width")); - CIntegerPtr heightCI(nodeMap.GetNode("Height")); + try + { + CIntegerPtr offsetX( nodeMap.GetNode("OffsetX") ); + CIntegerPtr offsetY( nodeMap.GetNode("OffsetY") ); + CIntegerPtr widthCI( nodeMap.GetNode("Width") ); + CIntegerPtr heightCI( nodeMap.GetNode("Height") ); - int oldOffsetX = offsetX->GetValue(); // if ERROR recover old value + int oldOffsetX = offsetX->GetValue(); //if ERROR recover old value int oldOffsetY = offsetY->GetValue(); - if (IsWritable(offsetX)) // On some cameras the offsets are read-only, + + if (IsWritable(offsetX)) // On some cameras the offsets are read-only, { - offsetX->SetValue(offsetX->GetMin()); + offsetX->SetValue( offsetX->GetMin() ); } if (IsWritable(offsetY)) { - offsetY->SetValue(offsetY->GetMin()); + offsetY->SetValue( offsetY->GetMin() ); } - if ((x + width) > widthCI->GetMax()) // GetMax depend on previous offset set - // so now is the maximum + if((x+width) > widthCI->GetMax()) //GetMax depend on previous offset set so now is the maximum { - printf("%s: ERROR in setReadoutArea: OffsetX + Width exceed maximum " - "allowed.", - this->ipAddress); - offsetX->SetValue(oldOffsetX); - lastOpRes = ERROR; - return ERROR; + printf("%s: ERROR in setReadoutArea: OffsetX + Width exceed maximum allowed.", this->ipAddress); + offsetX->SetValue( oldOffsetX ); + lastOpRes=ERROR; + return ERROR; } - if ((y + height) > heightCI->GetMax()) + if((y+height) > heightCI->GetMax()) { - printf("%s: ERROR in setReadoutArea: OffsetY + Height exceed maximum " - "allowed.", - this->ipAddress); - offsetY->SetValue(oldOffsetY); - lastOpRes = ERROR; - return ERROR; + printf("%s: ERROR in setReadoutArea: OffsetY + Height exceed maximum allowed.", this->ipAddress); + offsetY->SetValue( oldOffsetY ); + lastOpRes=ERROR; + return ERROR; } widthCI->SetValue(width); heightCI->SetValue(height); - offsetX->SetValue(x); - offsetY->SetValue(y); + offsetX->SetValue( x ); + offsetY->SetValue( y ); - cout << this->ipAddress << ": OffsetX : " << offsetX->GetValue() - << endl; - cout << this->ipAddress << ": OffsetY : " << offsetY->GetValue() - << endl; + cout << this->ipAddress << ": OffsetX : " << offsetX->GetValue() << endl; + cout << this->ipAddress << ": OffsetY : " << offsetY->GetValue() << endl; - cout << this->ipAddress << ": Width : " << widthCI->GetValue() - << endl; - cout << this->ipAddress << ": Height : " << heightCI->GetValue() - << endl; + cout << this->ipAddress << ": Width : " << widthCI->GetValue() << endl; + cout << this->ipAddress << ": Height : " << heightCI->GetValue() << endl; return SUCCESS; } - catch (const GenericException &e) + catch (const GenericException & e) { - cerr << "Error in setReadoutArea. Reason: " << e.GetDescription() << endl; - lastOpRes = ERROR; + cerr << "Error in setReadoutArea. Reason: " << e.GetDescription() << endl; + lastOpRes=ERROR; } return ERROR; } + int BASLER_ACA::setPixelFormat(char *pixelFormat) { - INodeMap &nodeMap = pCamera->GetNodeMap(); + cout << this->ipAddress << ": DEBUG TO REMOVE setPixelFormat " << endl; + INodeMap& nodeMap = pCamera->GetNodeMap(); CEnumerationPtr pFormat(nodeMap.GetNode("PixelFormat")); - if (IsAvailable(pFormat->GetEntryByName(pixelFormat)) == - false) // if not available set to Mono12 or Mono8 + try { - if (IsAvailable(pFormat->GetEntryByName("Mono12"))) + if(IsAvailable( pFormat->GetEntryByName(pixelFormat))==false) //if not available set to Mono12 or Mono8 + { + if(IsAvailable( pFormat->GetEntryByName("Mono12"))) { pFormat->FromString("Mono12"); - cout << this->ipAddress - << ": (WARNING) Selected PixelFormat is NOT available. Pixel format " - "set to Mono12" - << endl; + cout << this->ipAddress << ": (WARNING) Selected PixelFormat is NOT available. Pixel format set to Mono12" << endl; this->pixelFormat = CSU_PIX_FMT_GRAY16; this->Bpp = 2; return SUCCESS; @@ -514,585 +534,567 @@ int BASLER_ACA::setPixelFormat(char *pixelFormat) else { pFormat->FromString("Mono8"); - cout << this->ipAddress - << ": (WARNING) Selected PixelFormat is NOT available. PixelFormat " - "set to Mono8" - << endl; + cout << this->ipAddress << ": (WARNING) Selected PixelFormat is NOT available. PixelFormat set to Mono8" << endl; this->pixelFormat = CSU_PIX_FMT_GRAY8; this->Bpp = 1; return SUCCESS; - } + } } else { - pFormat->FromString(pixelFormat); - cout << this->ipAddress << ": PixelFormat set to : " << pFormat->ToString() - << endl; - if (strcmp(pixelFormat, "Mono8") == 0) - { - this->pixelFormat = CSU_PIX_FMT_GRAY8; - this->Bpp = 1; - } - if (strcmp(pixelFormat, "Mono12") == 0) - { - this->pixelFormat = CSU_PIX_FMT_GRAY16; - this->Bpp = 2; - } - if (strcmp(pixelFormat, "BayerRG8") == 0) - { - this->pixelFormat = CSU_PIX_FMT_BAYER_RGGB8; - this->Bpp = 1; - } - if (strcmp(pixelFormat, "YUV422Packed") == 0) - { - this->pixelFormat = CSU_PIX_FMT_YUV422_Packed; - this->Bpp = 2; - } - return SUCCESS; + pFormat->FromString(pixelFormat); + cout << this->ipAddress << ": PixelFormat set to : " << pFormat->ToString() << endl; + if(strcmp(pixelFormat, "Mono8")==0) + { + this->pixelFormat = CSU_PIX_FMT_GRAY8; + this->Bpp = 1; + } + if(strcmp(pixelFormat, "Mono12")==0) + { + this->pixelFormat = CSU_PIX_FMT_GRAY16; + this->Bpp = 2; + } + if(strcmp(pixelFormat, "BayerRG8")==0) + { + this->pixelFormat = CSU_PIX_FMT_BAYER_RGGB8; + this->Bpp = 1; + } + if(strcmp(pixelFormat, "YUV422Packed")==0) + { + this->pixelFormat = CSU_PIX_FMT_YUV422_Packed; + this->Bpp = 2; + } + return SUCCESS; } - - return ERROR; + }catch (const GenericException &e) + { + cout << this->ipAddress << ": DEBUG TO REMOVE exception in pixelFormat " << endl; + } + return ERROR; } + int BASLER_ACA::startAcquisition(int *width, int *height, int *payloadSize) { - INodeMap &nodeMap = pCamera->GetNodeMap(); - INode *node; - - // get width & height - this->width = *width = CIntegerPtr(nodeMap.GetNode("Width"))->GetValue(); - this->height = *height = CIntegerPtr(nodeMap.GetNode("Height"))->GetValue(); - - *payloadSize = this->width * this->height * this->Bpp; // no metadata - - printf("%s: width=%d.", this->ipAddress, this->width); - printf("%s: height=%d.", this->ipAddress, this->height); - printf("%s: Bpp=%d.\n", this->ipAddress, this->Bpp); - - // fede new 30/06/2017 due to incomplete grabbed frame error. The error advice - // to change iter-packed delay - pCamera->GevStreamChannelSelector.SetValue( - GevStreamChannelSelector_StreamChannel0); - pCamera->GevSCPD.SetValue(10000); // 1 tick should be 8ns from manual. So - // inter packed delay is now 80us. - // int64_t i = camera.GevSCPD.GetValue(); - - // Enable chunks in general. - node = nodeMap.GetNode("ChunkModeActive"); - if (IsWritable(node)) - { - CBooleanPtr(node)->SetValue(true); - } - else - { - throw RUNTIME_EXCEPTION("The camera doesn't support chunk features"); - } - // Enable time stamp chunks. - CEnumerationPtr ChunkSelector(nodeMap.GetNode("ChunkSelector")); - if (IsAvailable(ChunkSelector->GetEntryByName("Timestamp"))) - { - ChunkSelector->FromString("Timestamp"); - } - node = nodeMap.GetNode("ChunkEnable"); - CBooleanPtr(node)->SetValue(true); - - if (IsAvailable(ChunkSelector->GetEntryByName("PayloadCRC16"))) - { - ChunkSelector->FromString("PayloadCRC16"); - } - node = nodeMap.GetNode("ChunkEnable"); - CBooleanPtr(node)->SetValue(true); - - // new fede 20170918 - if (IsAvailable(ChunkSelector->GetEntryByName("ExposureTime"))) - { - ChunkSelector->FromString("ExposureTime"); - cout << this->ipAddress - << ": New ChunkSelector_ExposureTime: " << ChunkSelector->ToString() - << endl; - } - node = nodeMap.GetNode("ChunkEnable"); - CBooleanPtr(node)->SetValue(true); - - if (IsAvailable(ChunkSelector->GetEntryByName("GainAll"))) - { - ChunkSelector->FromString("GainAll"); - cout << this->ipAddress - << ": New ChunkSelector_GainAll: " << ChunkSelector->ToString() - << endl; - } - node = nodeMap.GetNode("ChunkEnable"); - CBooleanPtr(node)->SetValue(true); - - // CInstantCamera camera( device ); - // static const uint32_t c_countOfImagesToGrab = 100; - - // The parameter MaxNumBuffer can be used to control the count of buffers - // allocated for grabbing. The default value of this parameter is 10. - pCamera->MaxNumBuffer = 20; - - // Start the grabbing of c_countOfImagesToGrab images. - // The camera device is parameterized with a default configuration which - // sets up free-running continuous acquisition. - // pCamera->StartGrabbing( c_countOfImagesToGrab); - pCamera->StartGrabbing(); - - return SUCCESS; + INodeMap& nodeMap = pCamera->GetNodeMap(); + INode *node; + + //get width & height + this->width = *width = CIntegerPtr(nodeMap.GetNode("Width"))->GetValue(); + this->height = *height= CIntegerPtr(nodeMap.GetNode("Height"))->GetValue(); + + *payloadSize=this->width*this->height*this->Bpp; //no metadata + + printf("%s: width=%d.", this->ipAddress, this->width); + printf("%s: height=%d.", this->ipAddress, this->height); + printf("%s: Bpp=%d.\n", this->ipAddress, this->Bpp); + + //fede new 30/06/2017 due to incomplete grabbed frame error. The error advice to change iter-packed delay + pCamera->GevStreamChannelSelector.SetValue(GevStreamChannelSelector_StreamChannel0); + pCamera->GevSCPD.SetValue(10000); //1 tick should be 8ns from manual. So inter packed delay is now 80us. + //int64_t i = camera.GevSCPD.GetValue(); + + // Enable chunks in general. + node = nodeMap.GetNode("ChunkModeActive"); + if (IsWritable(node)) + { + CBooleanPtr(node)->SetValue(true); + } + else + { + throw RUNTIME_EXCEPTION( "The camera doesn't support chunk features"); + } + // Enable time stamp chunks. + CEnumerationPtr ChunkSelector(nodeMap.GetNode("ChunkSelector")); + if(IsAvailable(ChunkSelector->GetEntryByName("Timestamp"))) + { + ChunkSelector->FromString("Timestamp"); + } + node = nodeMap.GetNode("ChunkEnable"); + CBooleanPtr(node)->SetValue(true); + + if(IsAvailable(ChunkSelector->GetEntryByName("PayloadCRC16"))) + { + ChunkSelector->FromString("PayloadCRC16"); + } + node = nodeMap.GetNode("ChunkEnable"); + CBooleanPtr(node)->SetValue(true); + + //new fede 20170918 + if(IsAvailable(ChunkSelector->GetEntryByName("ExposureTime"))) + { + ChunkSelector->FromString("ExposureTime"); + cout << this->ipAddress << ": New ChunkSelector_ExposureTime: " << ChunkSelector->ToString() << endl; + } + node = nodeMap.GetNode("ChunkEnable"); + CBooleanPtr(node)->SetValue(true); + + if(IsAvailable(ChunkSelector->GetEntryByName("GainAll"))) + { + ChunkSelector->FromString("GainAll"); + cout << this->ipAddress << ": New ChunkSelector_GainAll: " << ChunkSelector->ToString() << endl; + } + node = nodeMap.GetNode("ChunkEnable"); + CBooleanPtr(node)->SetValue(true); + + // CInstantCamera camera( device ); + // static const uint32_t c_countOfImagesToGrab = 100; + + // The parameter MaxNumBuffer can be used to control the count of buffers + // allocated for grabbing. The default value of this parameter is 10. + pCamera->MaxNumBuffer = 20; + + // Start the grabbing of c_countOfImagesToGrab images. + // The camera device is parameterized with a default configuration which + // sets up free-running continuous acquisition. + // pCamera->StartGrabbing( c_countOfImagesToGrab); + pCamera->StartGrabbing(); + + return SUCCESS; } + + int BASLER_ACA::stopAcquisition() { - pCamera->StopGrabbing(); - printf("%s: Stop Acquisition\n", this->ipAddress); - return SUCCESS; + pCamera->StopGrabbing(); + printf("%s: Stop Acquisition\n", this->ipAddress); + return SUCCESS; } + int BASLER_ACA::getFrame(int *status, void *frame, void *metaData) { - // This smart pointer will receive the grab result data. - CGrabResultPtr ptrGrabResult; - - if (pCamera->IsGrabbing()) - { - // printf("getframe is grabbing\n"); - // Wait for an image and then retrieve it. A timeout of 5000 ms is used. - try - { - pCamera->RetrieveResult(5000, ptrGrabResult, - TimeoutHandling_ThrowException); - } - catch (const GenericException &e) - { - // Error handling. - cerr << this->ipAddress << "An exception occurred." << endl - << e.GetDescription() << endl; - // exitCode = 1; - *status = 3; // timeout - printf("-> 5s timeout reached in getFrame\n"); - } - if (ptrGrabResult->GrabSucceeded()) // Image grabbed successfully - { - *status = 1; // complete - unsigned int width = ptrGrabResult->GetWidth(); - unsigned int height = ptrGrabResult->GetHeight(); - const uint8_t *dataPtr = - (uint8_t *)ptrGrabResult - ->GetBuffer(); // use always char* also 4 bigger images - memcpy(frame, (unsigned char *)dataPtr, width * height * this->Bpp); - - // cout << this->ipAddress << ": Gray value of first pixel: " << - // (uint32_t) dataPtr[0] << endl << endl; - - // Check to see if a buffer containing chunk data has been received. - if (PayloadType_ChunkData != ptrGrabResult->GetPayloadType()) + // This smart pointer will receive the grab result data. + CGrabResultPtr ptrGrabResult; + + if(pCamera->IsGrabbing()) + { + //printf("getframe is grabbing\n"); + // Wait for an image and then retrieve it. A timeout of 5000 ms is used. + try{ + pCamera->RetrieveResult( 5000, ptrGrabResult, TimeoutHandling_ThrowException); + }catch (const GenericException &e) { - throw RUNTIME_EXCEPTION("Unexpected payload type received."); - } - // Since we have activated the CRC Checksum feature, we can check - // the integrity of the buffer first. - // Note: Enabling the CRC Checksum feature is not a prerequisite for using - // chunks. Chunks can also be handled when the CRC Checksum feature is - // deactivated. - if (ptrGrabResult->HasCRC() && ptrGrabResult->CheckCRC() == false) + // Error handling. + cerr << this->ipAddress << "An exception occurred." << endl << e.GetDescription() << endl; + // exitCode = 1; + *status=3; //timeout + printf("-> 5s timeout reached in getFrame\n"); + } + if (ptrGrabResult->GrabSucceeded()) // Image grabbed successfully { - throw RUNTIME_EXCEPTION("Image was damaged!"); - } - - int64_t ts; - if (ptrGrabResult->IsChunkDataAvailable()) - { - INodeMap &nodeMap = ptrGrabResult->GetChunkDataNodeMap(); - ts = CIntegerPtr(nodeMap.GetNode("ChunkTimestamp"))->GetValue(); - // printf("%I64d\n", ts); - } - - int gain = 0; - if (ptrGrabResult->IsChunkDataAvailable()) - { - INodeMap &nodeMap = ptrGrabResult->GetChunkDataNodeMap(); - gain = CIntegerPtr(nodeMap.GetNode("ChunkGainAll"))->GetValue(); - // printf("fede gainall chunk:%d\n", gain); - } - double exp = 0; - if (ptrGrabResult->IsChunkDataAvailable()) - { - INodeMap &nodeMap = ptrGrabResult->GetChunkDataNodeMap(); - exp = CFloatPtr(nodeMap.GetNode("ChunkExposureTime"))->GetValue(); - // printf("fede exp chunk:%f\n", exp); - } - - // printf("metadata size: %d\n", sizeof(BASLERMETADATA)); - BASLERMETADATA bMeta; - bMeta.gain = gain; - bMeta.exposure = exp; - bMeta.internalTemperature = this->internalTemperature; - bMeta.timestamp = ts; - memcpy(metaData, (unsigned char *)&bMeta, sizeof(BASLERMETADATA)); - - } // if (ptrGrabResult->GrabSucceeded() - else - { - cout << this->ipAddress - << ": Grab Error: " << ptrGrabResult->GetErrorCode() << " " - << ptrGrabResult->GetErrorDescription() << endl; - } - } // if(camera.IsGrabbing()) + *status=1; //complete + unsigned int width = ptrGrabResult->GetWidth(); + unsigned int height = ptrGrabResult->GetHeight(); + const uint8_t *dataPtr = (uint8_t *) ptrGrabResult->GetBuffer(); //use always char* also 4 bigger images + memcpy( frame , (unsigned char *)dataPtr, width*height*this->Bpp ); + + // cout << this->ipAddress << ": Gray value of first pixel: " << (uint32_t) dataPtr[0] << endl << endl; + + // Check to see if a buffer containing chunk data has been received. + if (PayloadType_ChunkData != ptrGrabResult->GetPayloadType()) + { + throw RUNTIME_EXCEPTION( "Unexpected payload type received."); + } + // Since we have activated the CRC Checksum feature, we can check + // the integrity of the buffer first. + // Note: Enabling the CRC Checksum feature is not a prerequisite for using + // chunks. Chunks can also be handled when the CRC Checksum feature is deactivated. + if (ptrGrabResult->HasCRC() && ptrGrabResult->CheckCRC() == false) + { + throw RUNTIME_EXCEPTION( "Image was damaged!"); + } + + int64_t ts; + if(ptrGrabResult->IsChunkDataAvailable()) + { + INodeMap& nodeMap = ptrGrabResult->GetChunkDataNodeMap(); + ts = CIntegerPtr(nodeMap.GetNode("ChunkTimestamp"))->GetValue(); + // printf("%I64d\n", ts); + } + + int gain=0; + if(ptrGrabResult->IsChunkDataAvailable()) + { + INodeMap& nodeMap = ptrGrabResult->GetChunkDataNodeMap(); + gain = CIntegerPtr(nodeMap.GetNode("ChunkGainAll"))->GetValue(); + //printf("fede gainall chunk:%d\n", gain); + } + double exp=0; + if(ptrGrabResult->IsChunkDataAvailable()) + { + INodeMap& nodeMap = ptrGrabResult->GetChunkDataNodeMap(); + exp = CFloatPtr(nodeMap.GetNode("ChunkExposureTime"))->GetValue(); + //printf("fede exp chunk:%f\n", exp); + } + + //printf("metadata size: %d\n", sizeof(BASLERMETADATA)); + BASLERMETADATA bMeta; + bMeta.gain=gain; + bMeta.exposure=exp; + bMeta.internalTemperature=this->internalTemperature; + bMeta.timestamp=ts; + memcpy( metaData , (unsigned char *)&bMeta, sizeof(BASLERMETADATA)); + + }// if (ptrGrabResult->GrabSucceeded() + else + { + cout << this->ipAddress << ": Grab Error: " << ptrGrabResult->GetErrorCode() << " " << ptrGrabResult->GetErrorDescription() << endl; + } + }//if(camera.IsGrabbing()) } -int BASLER_ACA::setStreamingMode(int streamingEnabled, bool autoAdjustLimit, - const char *streamingServer, int streamingPort, - unsigned int lowLim, unsigned int highLim, - int adjRoiX, int adjRoiY, int adjRoiW, - int adjRoiH, const char *deviceName) -{ - this->streamingEnabled = streamingEnabled; - - if (streamingEnabled) - { - memcpy(this->streamingServer, streamingServer, strlen(streamingServer) + 1); - memcpy(this->deviceName, deviceName, strlen(deviceName) + 1); - this->streamingPort = streamingPort; - this->autoAdjustLimit = autoAdjustLimit; - - this->lowLim = lowLim; - this->highLim = highLim; - - this->adjRoiX = adjRoiX; - this->adjRoiY = adjRoiY; - this->adjRoiW = adjRoiW; - this->adjRoiH = adjRoiH; - - this->minLim = 0; - this->maxLim = 4096; // max value for 12bit resolution of BASLER - } - return SUCCESS; -} -int BASLER_ACA::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) +int BASLER_ACA::setStreamingMode( int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) +{ + this->streamingEnabled = streamingEnabled; + + if( streamingEnabled ) + { + memcpy( this->streamingServer, streamingServer, strlen(streamingServer)+1 ); + memcpy( this->deviceName, deviceName, strlen(deviceName)+1 ); + this->streamingPort = streamingPort; + this->autoAdjustLimit = autoAdjustLimit; + + this->lowLim = lowLim; + this->highLim = highLim; + + this->adjRoiX = adjRoiX; + this->adjRoiY = adjRoiY; + this->adjRoiW = adjRoiW; + this->adjRoiH = adjRoiH; + + this->minLim= 0; + this->maxLim= 4096; //max value for 12bit resolution of BASLER + } + return SUCCESS; +} + + +int BASLER_ACA::setAcquisitionMode( int storeEnabled , int acqSkipFrameNumber) { - this->storeEnabled = storeEnabled; - this->acqSkipFrameNumber = acqSkipFrameNumber; - return SUCCESS; + this->storeEnabled = storeEnabled; + this->acqSkipFrameNumber = acqSkipFrameNumber; + return SUCCESS; } -int BASLER_ACA::setTriggerMode(int triggerMode, double burstDuration, - int numTrigger) + +int BASLER_ACA::setTriggerMode( int triggerMode, double burstDuration, int numTrigger ) { - this->triggerMode = triggerMode; - this->burstDuration = burstDuration; - this->numTrigger = numTrigger; + this->triggerMode = triggerMode; + this->burstDuration = burstDuration; + this->numTrigger = numTrigger; - return SUCCESS; + return SUCCESS; } int BASLER_ACA::softwareTrigger() { - this->startStoreTrg = 1; - return SUCCESS; + this->startStoreTrg = 1; + return SUCCESS; } -int BASLER_ACA::setTreeInfo(void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid) +int BASLER_ACA::setTreeInfo( void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) { - this->treePtr = treePtr; - this->framesNid = framesNid; - this->timebaseNid = timebaseNid; - this->framesMetadNid = framesMetadNid; - this->frame0TimeNid = frame0TimeNid; + this->treePtr = treePtr ; + this->framesNid = framesNid; + this->timebaseNid = timebaseNid; + this->framesMetadNid = framesMetadNid; + this->frame0TimeNid = frame0TimeNid; - return SUCCESS; + return SUCCESS; } /* void FLIR_SC65X::printLastError(const char *format, const char *msg) { - error[0] = 0; - if(msg) - sprintf(error, format, msg); - else - sprintf(error, format); + error[0] = 0; + if(msg) + sprintf(error, format, msg); + else + sprintf(error, format); } */ void BASLER_ACA::getLastError(char *msg) { - sprintf(msg, "%s:%s", this->ipAddress, (error[0] == 0) ? "" : error); + sprintf(msg, "%s:%s", this->ipAddress, (error[0]==0) ? "" : error); } int BASLER_ACA::stopFramesAcquisition() { - int count = 0; - - if (acqFlag == 0) - return SUCCESS; - - acqStopped = 0; - acqFlag = 0; - while (!acqStopped & count < 20) - { - count++; - usleep(50000); - } - - if (count == 20) - { - sprintf(error, "%s: Cannot stop acquisition loop\n", this->ipAddress); - return ERROR; - } - - return SUCCESS; + int count = 0; + + if (acqFlag == 0) + return SUCCESS; + + acqStopped = 0; + acqFlag = 0; + while( !acqStopped & count < 20 ) + { + count++; + usleep(50000); + } + + if(count == 20) + { + sprintf(error, "%s: Cannot stop acquisition loop\n", this->ipAddress); + return ERROR; + } + + return SUCCESS; } int BASLER_ACA::startFramesAcquisition() { - int frameTriggerCounter; - int frameCounter; - int frameStatus; - - int NtriggerCount = 0; - int burstNframe; - int rstatus; - int tcpStreamHandle = -1; - - int metaSize; - int enqueueFrameNumber; - float frameTime = 0.0; - float timeOffset = 0.0; // 20180605 - - void *saveList; - void *streamingList; - - void *frameBuffer; - unsigned char *metaData; - unsigned char *frame8bit; - - struct timeval tv; // manage frame timestamp in internal mode - int64_t timeStamp; - int64_t timeStamp0; - TreeNode *t0Node; - try - { - t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); - Data *nodeData = t0Node->getData(); - timeStamp0 = (int64_t)nodeData->getLong(); - } - catch (const MdsException &exc) - { - sprintf(error, "%s: Error getting frame0 time\n", this->ipAddress); - } - - if (triggerMode != 1) // in internal mode use the timebaseNid as T0 offset - // (ex. T_START_SPIDER) - { - TreeNode *tStartOffset; - try - { - tStartOffset = new TreeNode(timebaseNid, (Tree *)treePtr); - Data *nodeData = tStartOffset->getData(); - timeOffset = (float)nodeData->getFloatArray()[0]; - } - catch (const MdsException &exc) - { - sprintf(error, - "%s: Error getting timebaseNid (offset time set to 0.0s)\n", - this->ipAddress); - timeOffset = 0.0; - } - } - - if (this->Bpp == 1) - { - frameBuffer = (char *)calloc(1, width * height * sizeof(char)); - } - if (this->Bpp == 2) - { - frameBuffer = (short *)calloc(1, width * height * sizeof(short)); - } - frame8bit = (unsigned char *)calloc(1, width * height * sizeof(char)); - - metaSize = sizeof(BASLERMETADATA); - metaData = (unsigned char *)calloc(1, metaSize); - - camStartSave(&saveList); // # Initialize save frame Linked list reference - camStartStreaming( - &streamingList); // # Initialize streaming frame Linked list reference - burstNframe = (int)(burstDuration * frameRate + 1); - acqFlag = 1; - frameTriggerCounter = 0; - frameCounter = 0; - incompleteFrame = 0; - enqueueFrameNumber = 0; - startStoreTrg = 0; // manage the mdsplus saving process. SAVE always start - // with a SW or HW trigger. (0=no-save; 1=save) - - while (acqFlag) - { - getFrame(&frameStatus, frameBuffer, metaData); // get the frame - - if (storeEnabled) - { - if (triggerMode == 1) // External trigger source - { - - if ((frameStatus == 4) && - (startStoreTrg == 0)) // start data storing @ 1st trigger seen - // (trigger is on image header!) - { - startStoreTrg = 1; - printf("%s: TRIGGERED:\n", this->ipAddress); - } - - if (frameTriggerCounter == burstNframe) - { - triggered = 0; - startStoreTrg = 0; // disable storing - NtriggerCount++; - - printf("%s: ACQUIRED ALL FRAMES %d FOR TRIGGER : %d\n", - this->ipAddress, frameTriggerCounter, NtriggerCount); - frameTriggerCounter = 0; - - if (NtriggerCount == - numTrigger) // stop store when all trigger will be received - { - printf("%s: ACQUIRED ALL FRAME BURST: %d\n", this->ipAddress, - numTrigger); - storeEnabled = 0; - // break; - } - } // if (frameTriggerCounter == burstNframe) - } - else //( triggerMode == 1 ) //Internal trigger source - { - // Multiple trigger acquisition: first trigger save 64bit timestamp - timebaseNid = -1; // used in cammdsutils to use internal - triggered = 1; // debug - if (startStoreTrg == 1) - { - gettimeofday(&tv, NULL); - timeStamp = - ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // timeStamp [ms] - - if (timeStamp0 == 0) + int frameTriggerCounter; + int frameCounter; + int frameStatus; + + int NtriggerCount = 0; + int burstNframe; + int rstatus; + int tcpStreamHandle = -1; + + int metaSize; + int enqueueFrameNumber; + float frameTime = 0.0; + float timeOffset = 0.0; //20180605 + + void *saveList; + void *streamingList; + + void *frameBuffer; + unsigned char *metaData; + unsigned char *frame8bit; + + struct timeval tv; //manage frame timestamp in internal mode + int64_t timeStamp; + int64_t timeStamp0; + TreeNode *t0Node; + try{ + t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); + Data *nodeData = t0Node->getData(); + timeStamp0 = (int64_t)nodeData->getLong(); + }catch(MdsException *exc) + { + sprintf(error, "%s: Error getting frame0 time\n", this->ipAddress); + } + + + //if ( triggerMode != 1 ) //in internal mode use the timebaseNid as T0 offset (ex. T_START_SPIDER) + { //20210325: In external trigger, triggered on event must be set timeOffest + TreeNode *tStartOffset; + try{ + tStartOffset = new TreeNode(timebaseNid, (Tree *)treePtr); + Data *nodeData = tStartOffset->getData(); + timeOffset = (float)nodeData->getFloatArray()[0]; + }catch(MdsException *exc) { - Int64 *tsMDS = new Int64(timeStamp); - t0Node->putData(tsMDS); - timeStamp0 = timeStamp; + sprintf(error, "%s: Error getting timebaseNid (offset time set to 0.0s)\n", this->ipAddress); + timeOffset=0.0; } - else - { - frameTime = (float)((timeStamp - timeStamp0) / - 1000.0); // interval from first frame [s] - // printf("frameTime: %f", frameTime); - } - } // if startStoreTrg == 1 + } - if (frameTriggerCounter == burstNframe) + if(this->Bpp==1) { - startStoreTrg = 0; // disable storing - frameTriggerCounter = 0; - NtriggerCount++; - printf( - "%s: Stop Internal trigger acquisition time:%f dur:%f fps:%f\n", - this->ipAddress, frameTime, burstDuration, frameRate); - // storeEnabled=0; //infinite trigger until stop acquisition - // break; + frameBuffer = (char *) calloc(1, width * height * sizeof(char)); } - } // else Internal trigger source - } // if(storeEnabled) - - // frameStatus -> status=1 complete # status=2 incomplete # status=3 timeout - // # status=4 triggered frame + complete - if ((frameStatus != 3) && (storeEnabled == 1 && startStoreTrg == 1) && - (acqSkipFrameNumber <= 0 || - (frameTriggerCounter % (acqSkipFrameNumber + 1)) == 0)) - { - int frameTimeBaseIdx; - frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; - // printf("SAVE Frame : %d timebase Idx : %d\n", frameTriggerCounter, - // frameTimeBaseIdx); - - // CT la routine camSaveFrame utilizza il frame index in acquisizione. - // L'indice viene utilizzato per individuare nell'array della base - // temporale il tempo associato al frame. - - // Con Trigger interno viene utilizzato frameTime come tempo relativo allo - // 0; timebaseNid deve essere -1 - // camSaveFrame((void *)frameBuffer, width, height, frameTime, - // 14, (void *)treePtr, framesNid, timebaseNid, frameTimeBaseIdx, - // (void *)metaData, metaSize, framesMetadNid, saveList); - - camSaveFrame((void *)frameBuffer, width, height, frameTime + timeOffset, - 8 * this->Bpp, (void *)treePtr, framesNid, timebaseNid, - frameTimeBaseIdx, (void *)metaData, metaSize, framesMetadNid, - saveList); - enqueueFrameNumber++; - } - - if (streamingEnabled) - { - if (tcpStreamHandle == -1) - { - rstatus = - camOpenTcpConnection(streamingServer, streamingPort, - &tcpStreamHandle, width, height, pixelFormat); - if (rstatus != -1) + if(this->Bpp==2) { - printf("%s: Connected to FFMPEG on %s : %d\n", this->ipAddress, - streamingServer, streamingPort); + frameBuffer = (short *) calloc(1, width * height * sizeof(short)); } - else + frame8bit = (unsigned char *) calloc(1, width * height * sizeof(char)); + + metaSize = sizeof(BASLERMETADATA); + metaData = (unsigned char *)calloc(1, metaSize); + + camStartSave(&saveList); // # Initialize save frame Linked list reference + camStartStreaming(&streamingList); // # Initialize streaming frame Linked list reference + burstNframe = (int)(burstDuration * frameRate + 1. + 0.5);//CT 2021 03 20 + acqFlag = 1; + frameTriggerCounter = 0; + frameCounter = 0; + incompleteFrame = 0; + enqueueFrameNumber = 0; + startStoreTrg = 0; //manage the mdsplus saving process. SAVE always start with a SW or HW trigger. (0=no-save; 1=save) + + while ( acqFlag ) + { + getFrame( &frameStatus, frameBuffer, metaData); //get the frame + if(storeEnabled) { - printf("%s, Cannot connect to FFMPEG on %s : %d. Disable streaming\n", - this->ipAddress, streamingServer, streamingPort); - streamingEnabled = 0; + if ( triggerMode == 1 ) // External trigger source + { + + if ( (frameStatus == 4 || eventTrigger == 1 ) && (startStoreTrg == 0) ) //start data storing @ 1st trigger seen (trigger is on image header!) + { //CT In External Trigger Mode acquisitio is also triggered on MDSevent + startStoreTrg = 1; + + if( eventTrigger == 1 )//For debug in Event trigger mode is disable time base and use local time frame time stamp + { + timebaseNid = -1; + if(NtriggerCount == 0 ) timeStamp0 = 0; + } + + eventTrigger = 0; //CT Reset MDSplus trigger event flag + printf("%s: TRIGGERED:\n", this->ipAddress); + } + +/* Time stamp for acquisition in Event trigger */ + if(startStoreTrg == 1) + { + gettimeofday(&tv, NULL); + timeStamp = ((tv.tv_sec)*1000) + ((tv.tv_usec)/1000); // timeStamp [ms] + + if(timeStamp0==0) + { + Int64 *tsMDS = new Int64(timeStamp); + t0Node->putData(tsMDS); + timeStamp0=timeStamp; + printf("frameTime stamp 0: %f", timeStamp0); + } + else + { + frameTime = (float)((timeStamp-timeStamp0)/1000.0); //interval from first frame [s] + // printf("frameTime: %f", frameTime); + } + }//if startStoreTrg == 1 + +/*************************/ + + + + if (frameTriggerCounter == burstNframe) + { + triggered = 0; + startStoreTrg = 0; //disable storing + NtriggerCount++; + + printf("%s: ACQUIRED ALL FRAMES %d FOR TRIGGER : %d\n", this->ipAddress, frameTriggerCounter, NtriggerCount ); + frameTriggerCounter = 0; + + if ( NtriggerCount == numTrigger ) //stop store when all trigger will be received + { + printf("%s: ACQUIRED ALL FRAME BURST: %d\n", this->ipAddress, numTrigger ); + storeEnabled=0; + //break; + } + }//if (frameTriggerCounter == burstNframe) + + } + else //( triggerMode == 1 ) //Internal trigger source + { + //Multiple trigger acquisition: first trigger save 64bit timestamp + timebaseNid = -1; //used in cammdsutils to use internal + triggered = 1; //debug + if(startStoreTrg == 1) + { + gettimeofday(&tv, NULL); + timeStamp = ((tv.tv_sec)*1000) + ((tv.tv_usec)/1000); // timeStamp [ms] + + if(timeStamp0==0) + { + Int64 *tsMDS = new Int64(timeStamp); + t0Node->putData(tsMDS); + timeStamp0=timeStamp; + } + else + { + frameTime = (float)((timeStamp-timeStamp0)/1000.0); //interval from first frame [s] + // printf("frameTime: %f", frameTime); + } + }//if startStoreTrg == 1 + + if ( frameTriggerCounter == burstNframe ) + { + startStoreTrg = 0; //disable storing + frameTriggerCounter = 0; + NtriggerCount++; + printf("%s: Stop Internal trigger acquisition time:%f dur:%f fps:%f\n", this->ipAddress, frameTime, burstDuration, frameRate); + //storeEnabled=0; //infinite trigger until stop acquisition + //break; + } + }//else Internal trigger source + }//if(storeEnabled) + + + //frameStatus -> status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete + if( (frameStatus != 3 ) && ( storeEnabled == 1 && startStoreTrg == 1 ) && ( acqSkipFrameNumber <= 0 || (frameTriggerCounter % (acqSkipFrameNumber + 1) ) == 0 ) ) + { + int frameTimeBaseIdx; + frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; + //printf("SAVE Frame : %d timebase Idx : %d\n", frameTriggerCounter, frameTimeBaseIdx); + + // CT la routine camSaveFrame utilizza il frame index in acquisizione. L'indice viene + // utilizzato per individuare nell'array della base temporale il tempo associato al frame. + + // Con Trigger interno viene utilizzato frameTime come tempo relativo allo 0; timebaseNid deve essere -1 +// camSaveFrame((void *)frameBuffer, width, height, frameTime, 14, (void *)treePtr, framesNid, timebaseNid, frameTimeBaseIdx, (void *)metaData, metaSize, framesMetadNid, saveList); + //printf("%s: SAVE FRAME: %d of %d frame time %f\n", this->ipAddress, frameTriggerCounter+1, burstNframe, frameTime+timeOffset); + camSaveFrame((void *)frameBuffer, width, height, frameTime+timeOffset, 8*this->Bpp, (void *)treePtr, framesNid, timebaseNid, frameTimeBaseIdx, (void *)metaData, metaSize, framesMetadNid, saveList); + enqueueFrameNumber++; + + } + + if( streamingEnabled ) + { + if( tcpStreamHandle == -1) + { + rstatus = camOpenTcpConnection(streamingServer, streamingPort, &tcpStreamHandle, width, height, pixelFormat); + if( rstatus !=-1 ) + { + printf( "%s: Connected to FFMPEG on %s : %d\n", this->ipAddress, streamingServer, streamingPort); + } + else + { + printf( "%s, Cannot connect to FFMPEG on %s : %d. Disable streaming\n", this->ipAddress, streamingServer, streamingPort); + streamingEnabled = 0; + } + } + + //if ( (streamingSkipFrameNumber - 1 <= 0) || (frameCounter % ( streamingSkipFrameNumber - 1)) == 0 ) //20170327 - ORIGINAL + else if((this->frameRate<10) || (frameCounter % int(this->frameRate/10.0))==0) //send frame @ 10Hz. Reduce CPU usage. + { + camStreamingFrame( tcpStreamHandle, frameBuffer, width, height, pixelFormat, 0, autoAdjustLimit, &lowLim, &highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, this->deviceName, streamingList); + } + } // if( streamingEnabled ) + frameCounter++; //never resetted, used for frame timestamp + if ( startStoreTrg == 1 ) //increment saved frame index only if acquisition has been triggered + { + frameTriggerCounter++; } - } + }//endwhile - // if ( (streamingSkipFrameNumber - 1 <= 0) || (frameCounter % ( - // streamingSkipFrameNumber - 1)) == 0 ) //20170327 - ORIGINAL - else if ((this->frameRate < 10) || - (frameCounter % int(this->frameRate / 10.0)) == - 0) // send frame @ 10Hz. Reduce CPU usage. - { - camStreamingFrame(tcpStreamHandle, frameBuffer, width, height, - pixelFormat, 0, autoAdjustLimit, &lowLim, &highLim, - minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, - this->deviceName, streamingList); - } - } // if( streamingEnabled ) - frameCounter++; // never resetted, used for frame timestamp - if (startStoreTrg == - 1) // increment saved frame index only if acquisition has been triggered - { - frameTriggerCounter++; - } - } // endwhile - camStopSave(saveList); // Stop asynhronous store stream - camStopStreaming(streamingList); // Stop asynhronous frame streaming + int numSavedFrame = camSavedFrame(saveList); + int numBlackFrame = camBlackFrame(saveList); + - if (tcpStreamHandle != -1) - camCloseTcpConnection(&tcpStreamHandle); + camStopSave(saveList); // Stop asynhronous store stream + camStopStreaming(streamingList); // Stop asynhronous frame streaming - rstatus = stopAcquisition(); // stop camera acquisition - if (rstatus < 0) - sprintf(error, "%s: Cannot stop camera acquisition\n", this->ipAddress); + if( tcpStreamHandle != -1 ) + camCloseTcpConnection(&tcpStreamHandle); - free(frameBuffer); - free(frame8bit); - free(metaData); + rstatus = stopAcquisition(); //stop camera acquisition + if (rstatus < 0) + sprintf(error,"%s: Cannot stop camera acquisition\n", this->ipAddress); + + free(frameBuffer); + free(frame8bit); + free(metaData); - printf("%s: Acquisition Statistics : Total frames read %d, \n\t\t\t\t\tTotal " - "frames stored %d (expected %d), \n\t\t\t\t\tNumber of trigger %d " - "(expected %d), \n\t\t\t\t\tIncomplete frame %d\n", - this->ipAddress, frameCounter, enqueueFrameNumber, - 1 + numTrigger * - ((int)(burstDuration * (frameRate - acqSkipFrameNumber))), - NtriggerCount, numTrigger, incompleteFrame); + //printf("%s: Acquisition Statistics : Total frames read %d, \n\t\t\t\t\tTotal frames stored %d (expected %d), \n\t\t\t\t\tNumber of trigger %d (expected %d), \n\t\t\t\t\tIncomplete frame %d\n", this->ipAddress, frameCounter, enqueueFrameNumber, numTrigger * ( (int)( burstDuration * (frameRate - acqSkipFrameNumber)) + 1), NtriggerCount + startStoreTrg, numTrigger, incompleteFrame ); - acqStopped = 1; + printf("%s: Acquisition Statistics : Total frames read %d, \n\t\t\t\t\tTotal frames stored %d (expected %d), \n\t\t\t\t\tTotal black frame %d, \n\t\t\t\t\tNumber of trigger %d (expected %d), \n\t\t\t\t\tIncomplete frame %d\n", this->ipAddress, frameCounter, numSavedFrame, numTrigger * ( (int)( burstDuration * (frameRate - acqSkipFrameNumber)) + 1), numBlackFrame, NtriggerCount + startStoreTrg, numTrigger, incompleteFrame ); - return rstatus; + + acqStopped = 1; + + return rstatus; } + + diff --git a/device_support/basler/BASLERACA.h b/device_support/basler/BASLERACA.h index 6f03db7740..98d80e3601 100644 --- a/device_support/basler/BASLERACA.h +++ b/device_support/basler/BASLERACA.h @@ -1,8 +1,9 @@ +#include // Include files to use the PYLON API. -#include #include #include +#include // Settings for using Basler GigE cameras. #include @@ -13,8 +14,9 @@ typedef Pylon::CBaslerGigEGrabResultPtr GrabResultPtr_t; // Or use Camera_t::GrabResultPtr_t using namespace Basler_GigECameraParams; -using namespace Pylon; // Namespace for using pylon objects. -using namespace GenApi; // Namespace for using GenApi objects. +using namespace Pylon; // Namespace for using pylon objects. +using namespace GenApi; // Namespace for using GenApi objects. +using namespace MDSplus; enum FPS_ENUM { @@ -111,10 +113,46 @@ int Counted::count = 0; class BASLER_ACA : public Counted { + + class TriggerMdsEvent:public Event + { + private: + BASLER_ACA* baslerACA; + public: + TriggerMdsEvent(const char *name, BASLER_ACA* bACA):Event(name) + { + baslerACA = bACA; + } + + void run() + { + size_t bufSize; + const char *name = getName(); //Get the name of the event + char *date = getTime()->getDate(); //Get the event reception date in string format + const char *buf = getRaw(&bufSize); //Get raw data + char *str = new char[bufSize+1]; //Make it a string + memcpy(str, buf, bufSize); + str[bufSize] = 0; + //MDSevent trigger is set if camera is in acquisition, Frame store is enabled and camera is not saving frame. + //An event trigger received during acquisition can reset the trigger count to extend the acquisition + if(baslerACA->acqFlag && baslerACA->storeEnabled && baslerACA->startStoreTrg == 0) + { + printf("%s EVENT Trigger Start!!!!\n", baslerACA->ipAddress); + baslerACA->eventTrigger = 1; + } else { + printf("%s EVENT Trigger Reset!!!!\n", baslerACA->ipAddress); + baslerACA->eventTrigger = 0; + } + printf("%s RECEIVED EVENT %s AT %s WITH DATA %s Event Trig %d (%d,%d,%d)\n", baslerACA->ipAddress, name, date, str, baslerACA->eventTrigger); + } + }; + private: - IPylonDevice *pDevice; // device handle - Camera_t *pCamera; // camera handle + + IPylonDevice *pDevice; //device handle + Camera_t *pCamera; //camera handle char ipAddress[64]; + TriggerMdsEvent *trigEvent; int x; int y; @@ -131,6 +169,7 @@ class BASLER_ACA : public Counted int triggerMode; int startStoreTrg; int autoCalibration; + int eventTrigger; //CT on MDSplus event trigger flag int streamingEnabled; int streamingSkipFrameNumber; diff --git a/device_support/basler/main.cpp b/device_support/basler/main.cpp index 0e2ba32506..645ae0644b 100644 --- a/device_support/basler/main.cpp +++ b/device_support/basler/main.cpp @@ -7,31 +7,30 @@ using namespace MDSplus; #include #include -#define USETHECAMERA // this let to use the camera or if not defined to read \ - // data from a pulse file. -int main(int argc, char **argv) +#define USETHECAMERA //this let to use the camera or if not defined to read data from a pulse file. + + +int main(int argc, char **argv ) { - if ((argv[1] == NULL) || (argv[2] == NULL) || - (argv[3] == NULL)) // argv[4] is OPTIONAL - { - printf("Please insert: 1)tree name 2)shot number 3)number of frame to " - "acquire 4) Streaming Port (OPTIONAL)\n"); - exit(0); + if((argv[1]==NULL) || (argv[2]==NULL) || (argv[3]==NULL)) // argv[4] is OPTIONAL + { + printf("Please insert: 1)tree name 2)shot number 3)number of frame to acquire 4) Streaming Port (OPTIONAL)\n"); + exit(0); } - // MDSPLUS +//MDSPLUS int res; void *treePtr; - res = camOpenTree(argv[1], atoi(argv[2]), &treePtr); - if (res == -1) + res=camOpenTree(argv[1], atoi( argv[2] ), &treePtr); + if(res==-1) { - printf("Error opening tree...\n"); - exit(0); + printf("Error opening tree...\n"); + exit(0); } - Tree *tree; + Tree *tree; TreeNode *node; TreeNode *nodeMeta; int framesNid, timebaseNid, framesMetadNid, frame0TimeNid; @@ -39,37 +38,34 @@ int main(int argc, char **argv) try { tree = (Tree *)treePtr; - node = tree->getNode((char *)"\\BASLER::TOP:BASLER:FRAMES"); - framesNid = node->getNid(); - node = tree->getNode((char *)"\\BASLER::TOP:BASLER.TIMING:TIME_BASE"); - timebaseNid = node->getNid(); - node = tree->getNode((char *)"\\BASLER::TOP:BASLER:FRAMES_METAD"); - framesMetadNid = node->getNid(); - node = tree->getNode((char *)"\\BASLER::TOP:BASLER:FRAME0_TIME"); - frame0TimeNid = node->getNid(); - } - catch (const MdsException &exc) - { - std::cout << "ERROR reading data" << exc.what() << "\n"; - } + node=tree->getNode((char *)"\\BASLER::TOP:BASLER:FRAMES"); + framesNid=node->getNid(); + node=tree->getNode((char *)"\\BASLER::TOP:BASLER.TIMING:TIME_BASE"); + timebaseNid=node->getNid(); + node=tree->getNode((char *)"\\BASLER::TOP:BASLER:FRAMES_METAD"); + framesMetadNid=node->getNid(); + node=tree->getNode((char *)"\\BASLER::TOP:BASLER:FRAME0_TIME"); + frame0TimeNid=node->getNid(); + }catch ( MdsException *exc ) + { std::cout << "ERROR reading data" << exc->what() << "\n"; } + + // printf("frame node path: %s\n", node->getPath()); +//MDSPLUS END - // printf("frame node path: %s\n", node->getPath()); - // MDSPLUS END +//BASLER - // BASLER + int camHandle; + baslerOpen("192.168.54.96", &camHandle); //put camera ip - int camHandle; - baslerOpen("192.168.54.96", &camHandle); // put camera ip + int width=0; + int height=0; + int payloadSize=0; - int width = 0; - int height = 0; - int payloadSize = 0; + setTreeInfo( camHandle, treePtr, framesNid, timebaseNid, framesMetadNid, frame0TimeNid); + startAcquisition(camHandle, &width, &height, &payloadSize); + startFramesAcquisition(camHandle); + stopFramesAcquisition(camHandle); + stopAcquisition(camHandle); + baslerClose(camHandle); - setTreeInfo(camHandle, treePtr, framesNid, timebaseNid, framesMetadNid, - frame0TimeNid); - startAcquisition(camHandle, &width, &height, &payloadSize); - startFramesAcquisition(camHandle); - stopFramesAcquisition(camHandle); - stopAcquisition(camHandle); - baslerClose(camHandle); } diff --git a/device_support/caen/caenInterface.cpp b/device_support/caen/caenInterface.cpp index 0be3da67c1..d28a63b4c4 100644 --- a/device_support/caen/caenInterface.cpp +++ b/device_support/caen/caenInterface.cpp @@ -31,6 +31,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include using namespace MDSplus; + int caenLibDebug = 1; ////////////////////////////////////////////////////////////// @@ -41,10 +42,29 @@ int caenLibDebug = 1; // sampling rate = 100MHz // gain at 10 MHz is about 1. #define FILTER_LEN 25 -int16_t coeffs[FILTER_LEN] = {547, 469, 95, -872, -2261, -3518, -3845, - -2528, 677, 5300, 10204, 13951, 15353, 13951, - 10204, 5300, 677, -2528, -3845, -3518, -2261, - -872, 95, 469, 547}; +int16_t coeffs[ FILTER_LEN ] = +{ 547, 469, 95, +-872,-2261, +-3518, +-3845, +-2528, +677, +5300, +10204, +13951, +15353, +13951, +10204, +5300, +677, +-2528, +-3845, +-3518, +-2261, +-872, +95, +469, +547}; #define SAMPLES 8000 @@ -56,456 +76,440 @@ int16_t coeffs[FILTER_LEN] = {547, 469, 95, -872, -2261, -3518, -3845, // buffer to hold all of the input samples #define BUFFER_LEN (MAX_FLT_LEN - 1 + MAX_INPUT_LEN) // array to hold input samples -int16_t insamp[BUFFER_LEN]; +int16_t insamp[ BUFFER_LEN ]; // FIR init -void firFixedInit(void) { memset(insamp, 0, sizeof(insamp)); } +void firFixedInit( void ) +{ + memset( insamp, 0, sizeof( insamp ) ); +} // the FIR filter function -void firFixed(int16_t *coeffs, int16_t *input, int16_t *output, int length, - int filterLength) +void firFixed( int16_t *coeffs, int16_t *input, int16_t *output, int length, int filterLength ) { - int32_t acc; // accumulator for MACs - int16_t *coeffp; // pointer to coefficients - int16_t *inputp; // pointer to input samples - int n; - int k; - // put the new samples at the high end of the buffer - memcpy(&insamp[filterLength - 1], input, length * sizeof(int16_t)); - // apply the filter to each input sample - for (n = 0; n < length; n++) - { - // calculate output n - coeffp = coeffs; - inputp = &insamp[filterLength - 1 + n]; - // load rounding constant - acc = 1 << 14; - // perform the multiply-accumulate - for (k = 0; k < filterLength; k++) - { - acc += (int32_t)(*coeffp++) * (int32_t)(*inputp--); - } - // saturate the result - if (acc > 0x3fffffff) - { - acc = 0x3fffffff; - } - else if (acc < -0x40000000) - { - acc = -0x40000000; - } - // convert from Q30 to Q15 - output[n] = (int16_t)(acc >> 15); - } - // shift input samples back in time for next time - memmove(&insamp[0], &insamp[length], (filterLength - 1) * sizeof(int16_t)); + int32_t acc; // accumulator for MACs + int16_t *coeffp; // pointer to coefficients + int16_t *inputp; // pointer to input samples + int n; + int k; + // put the new samples at the high end of the buffer + memcpy( &insamp[filterLength - 1], input, length * sizeof(int16_t) ); + // apply the filter to each input sample + for ( n = 0; n < length; n++ ) + { + // calculate output n + coeffp = coeffs; + inputp = &insamp[filterLength - 1 + n]; + // load rounding constant + acc = 1 << 14; + // perform the multiply-accumulate + for ( k = 0; k < filterLength; k++ ) { + acc += (int32_t)(*coeffp++) * (int32_t)(*inputp--); + } + // saturate the result + if ( acc > 0x3fffffff ) { + acc = 0x3fffffff; + } else if ( acc < -0x40000000 ) { + acc = -0x40000000; + } + // convert from Q30 to Q15 + output[n] = (int16_t)(acc >> 15); + } + // shift input samples back in time for next time + memmove( &insamp[0], &insamp[length], + (filterLength - 1) * sizeof(int16_t) ); } + ////////////////////////////////////////////////////////////// // Filter Code Definitions End ////////////////////////////////////////////////////////////// -// Support class for enqueueing storage requests -class SaveItem -{ - void *segment; - char dataType; - int segmentSize; - int startIdx_c; - int endIdx_c; - int segmentCount; - int dataNid; - int clockNid; - int triggerNid; - void *treePtr; - SaveItem *nxt; - -public: - SaveItem(void *segment, int segmentSize, char dataType, int startIdx_c, - int endIdx_c, int segmentCount, int dataNid, int clockNid, - int triggerNid, void *treePtr) - { - this->segment = segment; - this->segmentSize = segmentSize; - this->dataType = dataType; - this->startIdx_c = startIdx_c; - this->endIdx_c = endIdx_c; - this->segmentCount = segmentCount; - this->dataNid = dataNid; - this->clockNid = clockNid; - this->treePtr = treePtr; - this->triggerNid = triggerNid; - nxt = 0; - } - - void setNext(SaveItem *itm) { nxt = itm; } - - SaveItem *getNext() { return nxt; } - - void save() - { - - TreeNode *dataNode = new TreeNode(dataNid, (Tree *)treePtr); - TreeNode *clockNode = new TreeNode(clockNid, (Tree *)treePtr); - TreeNode *triggerNode = new TreeNode(triggerNid, (Tree *)treePtr); - - Data *startTime; - Data *endTime; - Data *dim; - Data *startIdx = new Int32(startIdx_c); - Data *endIdx = new Int32(endIdx_c); - Data *segCount = new Int32(segmentCount); - - startTime = compileWithArgs("$[$]+slope_of($)*$", (Tree *)treePtr, 4, - triggerNode, segCount, clockNode, startIdx); - endTime = compileWithArgs("$[$]+slope_of($)*$", (Tree *)treePtr, 4, - triggerNode, segCount, clockNode, endIdx); - - /* - dim = compileWithArgs("build_dim(build_window($, $, $[$]), - build_slope( slope_of($) ) )", (Tree *)treePtr, 5, startIdx, endIdx, - triggerNode, segCount, clockNode); - */ - dim = compileWithArgs( - "build_range($[$]+slope_of($)*$, $[$]+slope_of($)*($-1), slope_of($))", - (Tree *)treePtr, 9, triggerNode, segCount, clockNode, startIdx, - triggerNode, segCount, clockNode, endIdx, clockNode); - - try + +//Support class for enqueueing storage requests +class SaveItem { + void *segment; + char dataType; + int segmentSize; + int startIdx_c; + int endIdx_c; + int segmentCount; + int dataNid; + int clockNid; + int triggerNid; + void *treePtr; + SaveItem *nxt; + + public: + SaveItem(void *segment, int segmentSize, char dataType, int startIdx_c, int endIdx_c, int segmentCount, int dataNid, int clockNid, int triggerNid, void *treePtr) { + this->segment = segment; + this->segmentSize = segmentSize; + this->dataType = dataType; + this->startIdx_c = startIdx_c; + this->endIdx_c = endIdx_c; + this->segmentCount = segmentCount; + this->dataNid = dataNid; + this->clockNid = clockNid; + this->treePtr = treePtr; + this->triggerNid = triggerNid; + nxt = 0; + } - switch (dataType) - { - case DTYPE_W: - { - Int16Array *sData = new Int16Array((short *)segment, segmentSize); - printf("Save short data segment idx %d endIdx_c %d\n", segmentCount, - endIdx_c); - dataNode->makeSegment(startTime, endTime, dim, sData); - deleteData(sData); - } - break; - case DTYPE_F: - { - Float32Array *fData = new Float32Array((float *)segment, segmentSize); - printf("Save flat data segment idx %d endIdx_c %d\n", segmentCount, - endIdx_c); - dataNode->makeSegment(startTime, endTime, dim, fData); - deleteData(fData); - } - break; - } - free(segment); - deleteData(startIdx); - deleteData(endIdx); - deleteData(startTime); - deleteData(endTime); - deleteData(segCount); + void setNext(SaveItem *itm) + { + nxt = itm; } - catch (const MdsException &exc) + + SaveItem *getNext() { - printf("Cannot put segment: %s\n", exc.what()); + return nxt; } - delete dataNode; - delete clockNode; - delete triggerNode; - } + + void save() + { + + TreeNode *dataNode = new TreeNode(dataNid, (Tree *)treePtr); + TreeNode *clockNode = new TreeNode(clockNid, (Tree *)treePtr); + TreeNode *triggerNode = new TreeNode(triggerNid, (Tree *)treePtr); + + + Data *startTime; + Data *endTime; + Data *dim; + Data *startIdx = new Int32(startIdx_c); + Data *endIdx = new Int32(endIdx_c); + Data *segCount = new Int32(segmentCount); + + + startTime = compileWithArgs("DATA($)[$]+slope_of($)*$",(Tree *)treePtr, 4, triggerNode, segCount, clockNode, startIdx); + endTime = compileWithArgs("DATA($)[$]+slope_of($)*$",(Tree *)treePtr, 4, triggerNode, segCount, clockNode, endIdx); + +/* + dim = compileWithArgs("build_dim(build_window($, $, $[$]), build_slope( slope_of($) ) )", (Tree *)treePtr, 5, startIdx, endIdx, triggerNode, segCount, clockNode); +*/ + dim = compileWithArgs("build_range(DATA($)[$]+slope_of($)*$, DATA($)[$]+slope_of($)*($-1), slope_of($))", (Tree *)treePtr, + 9, triggerNode, segCount, clockNode, startIdx, triggerNode, segCount, clockNode, endIdx, clockNode); + + + + + try + { + + switch( dataType ) + { + case DTYPE_W: + { + Int16Array *sData = new Int16Array((short *)segment, segmentSize); + printf("Save short data segment idx %d endIdx_c %d\n", segmentCount, endIdx_c ); + dataNode->makeSegment(startTime, endTime, dim, sData); + deleteData(sData); + } + break; + case DTYPE_F: + { + Float32Array *fData = new Float32Array((float *)segment, segmentSize); + printf("Save flat data segment idx %d endIdx_c %d\n", segmentCount, endIdx_c ); + dataNode->makeSegment(startTime, endTime, dim, fData); + deleteData(fData); + } + break; + } + free(segment); + deleteData(startIdx); + deleteData(endIdx); + deleteData(startTime); + deleteData(endTime); + deleteData(segCount); + + } + catch(MdsException *exc) + { + printf("Cannot put segment: %s\n", exc->what()); + } + delete dataNode; + delete clockNode; + delete triggerNode; + } + }; extern "C" void *handleSave(void *listPtr); class SaveList { -public: - pthread_cond_t itemAvailable; - pthread_t thread; - bool threadCreated; - SaveItem *saveHead, *saveTail; - bool stopReq; - pthread_mutex_t mutex; - -public: - SaveList() - { - pthread_mutex_init(&mutex, NULL); - pthread_cond_init(&itemAvailable, NULL); - saveHead = saveTail = NULL; - stopReq = false; - threadCreated = false; - } - - void addItem(void *segment, int segmentSize, char dataType, int startIdx_c, - int endIdx_c, int segmentCount, int dataNid, int clockNid, - int triggerNid, void *treePtr) - { - // printf("add Item\n"); - - int noFilter = 1; - void *segmentc = calloc(1, segmentSize * sizeof(short)); - int size; - - if (noFilter) + public: + pthread_cond_t itemAvailable; + pthread_t thread; + bool threadCreated; + SaveItem *saveHead, *saveTail; + bool stopReq; + pthread_mutex_t mutex; + public: + + SaveList() { - memcpy(segmentc, segment, segmentSize * sizeof(short)); + pthread_mutex_init(&mutex, NULL); + pthread_cond_init(&itemAvailable, NULL); + saveHead = saveTail = NULL; + stopReq = false; + threadCreated = false; } - else + + void addItem(void *segment, int segmentSize, char dataType, int startIdx_c, int endIdx_c, int segmentCount, int dataNid, int clockNid, int triggerNid, void *treePtr) { - int cIdx = 0, currSize; - // initialize the filter - firFixedInit(); - // process all of the samples - currSize = segmentSize; - size = SAMPLES; - printf("----Start Filter\n"); - while (currSize > 0) - { - size = (size > currSize ? currSize : size); - firFixed(coeffs, &((int16_t *)segment)[cIdx], - &((int16_t *)segmentc)[cIdx], size, FILTER_LEN); - currSize -= size; - cIdx += size; - } +//printf("add Item\n"); + + int noFilter = 1; + void *segmentc = calloc(1, segmentSize * sizeof(short)); + int size; + + if( noFilter ) + { + memcpy(segmentc, segment, segmentSize * sizeof(short) ); + } + else + { + int cIdx = 0, currSize; + // initialize the filter + firFixedInit(); + // process all of the samples + currSize = segmentSize; + size = SAMPLES; +printf("----Start Filter\n"); + while(currSize > 0) + { + size = (size > currSize ? currSize : size); + firFixed( coeffs, &((int16_t *)segment)[cIdx], &((int16_t *)segmentc)[cIdx], size, FILTER_LEN ); + currSize -= size; + cIdx += size; + } + } + + SaveItem *newItem = new SaveItem(segmentc, segmentSize, dataType, startIdx_c, endIdx_c, segmentCount, dataNid, clockNid, triggerNid, treePtr); + pthread_mutex_lock(&mutex); + if(saveHead == NULL) + saveHead = saveTail = newItem; + else + { + saveTail->setNext(newItem); + saveTail = newItem; + } + pthread_cond_signal(&itemAvailable); + pthread_mutex_unlock(&mutex); } - - SaveItem *newItem = - new SaveItem(segmentc, segmentSize, dataType, startIdx_c, endIdx_c, - segmentCount, dataNid, clockNid, triggerNid, treePtr); - pthread_mutex_lock(&mutex); - if (saveHead == NULL) - saveHead = saveTail = newItem; - else + void executeItems() { - saveTail->setNext(newItem); - saveTail = newItem; + while(true) + { + pthread_mutex_lock(&mutex); + if(stopReq && saveHead == NULL) + { + pthread_mutex_unlock(&mutex); + pthread_exit(NULL); + } + + while(saveHead == NULL) + { + pthread_cond_wait(&itemAvailable, &mutex); + if(stopReq && saveHead == NULL) + { + pthread_mutex_unlock(&mutex); + pthread_exit(NULL); + } + /* + int nItems = 0; + for(SaveItem *itm = saveHead; itm; itm = itm->getNext(), nItems++); + if(nItems > 2) printf("THREAD ACTIVATED: %d items pending\n", nItems); + */ + } + SaveItem *currItem = saveHead; + saveHead = saveHead->getNext(); + /* + int nItems = 0; + for(SaveItem *itm = saveHead; itm; itm = itm->getNext(), nItems++); + if(nItems > 2) printf("THREAD ACTIVATED: %d items pending\n", nItems); + */ + pthread_mutex_unlock(&mutex); + currItem->save(); + delete currItem; + } } - pthread_cond_signal(&itemAvailable); - pthread_mutex_unlock(&mutex); - } - void executeItems() - { - while (true) + void start() { - pthread_mutex_lock(&mutex); - if (stopReq && saveHead == NULL) - { - pthread_mutex_unlock(&mutex); - pthread_exit(NULL); - } - - while (saveHead == NULL) - { - pthread_cond_wait(&itemAvailable, &mutex); - if (stopReq && saveHead == NULL) - { - pthread_mutex_unlock(&mutex); - pthread_exit(NULL); - } - /* - int nItems = 0; - for(SaveItem *itm = saveHead; itm; itm = itm->getNext(), - nItems++); if(nItems > 2) printf("THREAD ACTIVATED: %d items - pending\n", nItems); - */ - } - SaveItem *currItem = saveHead; - saveHead = saveHead->getNext(); - /* - int nItems = 0; - for(SaveItem *itm = saveHead; itm; itm = itm->getNext(), - nItems++); if(nItems > 2) printf("THREAD ACTIVATED: %d items - pending\n", nItems); - */ - pthread_mutex_unlock(&mutex); - currItem->save(); - delete currItem; + pthread_create(&thread, NULL, handleSave, (void *)this); + threadCreated = true; } - } - void start() - { - pthread_create(&thread, NULL, handleSave, (void *)this); - threadCreated = true; - } - void stop() - { - stopReq = true; - pthread_cond_signal(&itemAvailable); - if (threadCreated) + void stop() { - pthread_join(thread, NULL); - printf("SAVE THREAD TERMINATED\n"); + stopReq = true; + pthread_cond_signal(&itemAvailable); + if(threadCreated) + { + pthread_join(thread, NULL); + printf("SAVE THREAD TERMINATED\n"); + } } - } -}; + }; + extern "C" void *handleSave(void *listPtr) { - SaveList *list = (SaveList *)listPtr; - list->executeItems(); - return NULL; + SaveList *list = (SaveList *)listPtr; + list->executeItems(); + return NULL; } extern "C" void startSave(void **retList) { - SaveList *saveList = new SaveList; - saveList->start(); - *retList = (void *)saveList; + SaveList *saveList = new SaveList; + saveList->start(); + *retList = (void *)saveList; } extern "C" void stopSave(void *listPtr) { - if (listPtr) - { - SaveList *list = (SaveList *)listPtr; - list->stop(); - delete list; - } + if(listPtr) + { + SaveList *list = (SaveList *)listPtr; + list->stop(); + delete list; + } } + extern "C" void openTree(char *name, int shot, void **treePtr) { - try - { - Tree *tree = new Tree(name, shot); - *treePtr = (void *)tree; - } - catch (const MdsException &exc) - { - printf("Cannot open tree %s %d: %s\n", name, shot, exc.what()); - } + try { + Tree *tree = new Tree(name, shot); + *treePtr = (void *)tree; + } + catch(MdsException *exc) + { + printf("Cannot open tree %s %d: %s\n", name, shot, exc->what()); + } } + #define MAX_CHANNELS 4 struct segment_struct { - int eventSize; - int boardGroup; - int counter; - int time; - short *data; + int eventSize; + int boardGroup; + int counter; + int time; + short *data; }; -void onError(const char *msg) { printf("Error : %s", msg); } +void onError(const char *msg ) +{ + printf("Error : %s", msg); +} -extern "C" int -readAndSaveSegments(int32_t handle, int32_t vmeAddress, int numChannels, - int nActChans, int segmentSamples, int segmentSize, - int startIdx, int endIdx, int pts, int useCounter, - int chanMask, int segmentCounter, int numSegment, - int *dataNidPtr, int clockNid, int triggerNid, - void *treePtr, void *saveListPtr) +extern "C" int readAndSaveSegments(int32_t handle, int32_t vmeAddress, int numChannels, int nActChans, int segmentSamples, int segmentSize, int startIdx, int endIdx, int pts, int useCounter, int chanMask, int segmentCounter, int numSegment, int *dataNidPtr, int clockNid, int triggerNid, void *treePtr, void *saveListPtr) { - // numSegmens < 0 for Continuous acquisition , numSegmens > 0 for transient - // recorder acquisition - - int actSegments = 0; - int status; - struct segment_struct segment; - short *channels[MAX_CHANNELS]; - SaveList *saveList = (SaveList *)saveListPtr; - - int currStartIdx = segmentSamples - pts + startIdx; - int currEndIdx = segmentSamples - pts + endIdx; - int currChanSamples = currEndIdx - currStartIdx; - - // Read number of buffers - status = CAENVME_ReadCycle(handle, (vmeAddress + 0x812C), &actSegments, - cvA32_S_DATA, cvD32); - if (status != 0) - { - onError("Error reading number of acquired segments"); - return 0; - } - - if (caenLibDebug) - printf("segmentCounter %d actSegments %d nActChans %d segmentSamples %d " - "currChanSamples %d\n", - segmentCounter, actSegments, nActChans, segmentSamples, - currChanSamples); - - short *buff = - (short *)calloc(1, 16 + nActChans * segmentSamples * sizeof(short)); - - for (int chan = 0; chan < numChannels; chan++) - { - channels[chan] = - (short *)calloc(1, currChanSamples * actSegments * sizeof(short)); - } - - for (int segmentIdx = 0; segmentIdx < actSegments; segmentIdx++) - { - - int retLen = 0; - // printf("Read CAENVME_FIFOBLTReadCycle %d vmeAddress %d segmentSize %d\n", - // segmentIdx, vmeAddress, segmentSize); - status = CAENVME_FIFOBLTReadCycle(handle, vmeAddress, buff, segmentSize, - cvA32_S_DATA, cvD64, &retLen); - - if (status != 0) - { - free(buff); - onError("ASYNCH: Error reading data segment"); - return 0; - } +// numSegmens < 0 for Continuous acquisition , numSegmens > 0 for transient recorder acquisition + + int actSegments = 0; + int status; + struct segment_struct segment; + short* channels[MAX_CHANNELS]; + SaveList *saveList = (SaveList *)saveListPtr; + + + int currStartIdx = segmentSamples - pts + startIdx; + int currEndIdx = segmentSamples - pts + endIdx; + int currChanSamples = currEndIdx - currStartIdx; + + + // Read number of buffers + status = CAENVME_ReadCycle(handle, (vmeAddress + 0x812C), &actSegments, cvA32_S_DATA, cvD32); + if ( status != 0 ) + { + onError("Error reading number of acquired segments"); + return segmentCounter; + } + + if ( caenLibDebug ) printf("segmentCounter %d actSegments %d nActChans %d segmentSamples %d currChanSamples %d\n", segmentCounter, actSegments, nActChans, segmentSamples, currChanSamples); + + short *buff = (short *)calloc( 1, 16 + nActChans * segmentSamples * sizeof(short) ); + + for(int chan = 0; chan < numChannels; chan++) + { + channels[chan] = (short *)calloc(1, currChanSamples * actSegments * sizeof(short)); + } + + for( int segmentIdx = 0; segmentIdx < actSegments; segmentIdx++ ) + { + + int retLen = 0; + printf("Read CAENVME_FIFOBLTReadCycle %d vmeAddress %d segmentSize %d\n", segmentIdx, vmeAddress, segmentSize); + status = CAENVME_FIFOBLTReadCycle(handle, vmeAddress, buff, segmentSize, cvA32_S_DATA, cvD64, &retLen); + + if ( status != 0 ) + { + printf("ASYNCH: Error reading data segment. Status: %d Ret Len: %d\n", status, retLen); + free(buff); + return 0; + } + + memcpy(&segment, buff, 4 * sizeof(int) ); + + int actSize = 4 * (segment.eventSize & 0x0fffffff); + int counter = segment.time/2; + int sizeInInts = (segment.eventSize & 0x0fffffff) - 4; + int chanSizeInInts = sizeInInts/nActChans; + int chanSizeInShorts = chanSizeInInts * 2; + + if( caenLibDebug ) printf( "Read actSize %d counter %d sizeInInts %d retLen %d Index %d\n", actSize, counter, sizeInInts, retLen, segment.time % actSize ); + + + for( int chan = 0; chan < numChannels; chan++) + { + if ( (chanMask & (1 << chan)) != 0 ) + { + if( caenLibDebug ) + printf("---Seg Idx %d - channels[%d][%d : %d], &buff[%d : %d]\n", segmentIdx, chan, segmentIdx * currChanSamples, currChanSamples, + 16 + chan * chanSizeInShorts + currStartIdx, currChanSamples); + + memcpy( &channels[chan][segmentIdx * currChanSamples], &buff[16 + chan * chanSizeInShorts + currStartIdx], currChanSamples * sizeof(short) ); + } + } + } - memcpy(&segment, buff, 4 * sizeof(int)); + free(buff); + + if ( actSegments > 0 ) + { + + for( int chan = 0; chan < numChannels; chan++) + { + if ( (chanMask & (1 << chan)) != 0 ) + { + for( int seg = 0; seg < actSegments; seg++ ) + { + if( numSegment > 0 && segmentCounter + seg > numSegment ) + { + if( caenLibDebug )printf("skip seg %d for channel %d\n", (segmentCounter + seg), chan); + break; + } + saveList->addItem((void *)&channels[chan][seg * currChanSamples], currChanSamples, + DTYPE_W, startIdx, endIdx, (segmentCounter + seg), dataNidPtr[chan], clockNid, triggerNid, treePtr); + } + } + free(channels[chan]); + } + } + + if( numSegment > 0 && segmentCounter + actSegments > numSegment ) + return ( numSegment ); + else + return ( segmentCounter + actSegments ); + +} - int actSize = 4 * (segment.eventSize & 0x0fffffff); - int counter = segment.time / 2; - int sizeInInts = (segment.eventSize & 0x0fffffff) - 4; - int chanSizeInInts = sizeInInts / nActChans; - int chanSizeInShorts = chanSizeInInts * 2; - if (caenLibDebug) - printf("Read actSize %d counter %d sizeInInts %d retLen %d Index %d\n", - actSize, counter, sizeInInts, retLen, segment.time % actSize); - for (int chan = 0; chan < numChannels; chan++) - { - if ((chanMask & (1 << chan)) != 0) - { - if (caenLibDebug) - printf("---Seg Idx %d - channels[%d][%d : %d], &buff[%d : %d]\n", - segmentIdx, chan, segmentIdx * currChanSamples, - currChanSamples, 16 + chan * chanSizeInShorts + currStartIdx, - currChanSamples); - - memcpy(&channels[chan][segmentIdx * currChanSamples], - &buff[16 + chan * chanSizeInShorts + currStartIdx], - currChanSamples * sizeof(short)); - } - } - } - free(buff); - if (actSegments > 0) - { - - for (int chan = 0; chan < numChannels; chan++) - { - if ((chanMask & (1 << chan)) != 0) - { - for (int seg = 0; seg < actSegments; seg++) - { - if (numSegment > 0 && segmentCounter + seg > numSegment) - { - if (caenLibDebug) - printf("skip seg %d for channel %d\n", (segmentCounter + seg), - chan); - break; - } - saveList->addItem((void *)&channels[chan][seg * currChanSamples], - currChanSamples, DTYPE_W, startIdx, endIdx, - (segmentCounter + seg), dataNidPtr[chan], clockNid, - triggerNid, treePtr); - } - } - free(channels[chan]); - } - } - - if (numSegment > 0 && segmentCounter + actSegments > numSegment) - return (numSegment); - else - return (segmentCounter + actSegments); -} diff --git a/device_support/camera_utils/Makefile b/device_support/camera_utils/Makefile index 86e1ec03a8..f3b8ba2736 100755 --- a/device_support/camera_utils/Makefile +++ b/device_support/camera_utils/Makefile @@ -2,8 +2,8 @@ CC=g++ #TO ENABLE DEBUG MESSAGES ADD OPTION -DDEBUG -CFLAGSmdsutils= -c -o3 -fPIC -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES -I. -I$(MDSPLUS_DIR)/include -CFLAGSstreamutils= -c -o3 -fPIC -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES -I. +CFLAGSmdsutils= -c -std=c++11 -O3 -fPIC -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES -I. -I$(MDSPLUS_DIR)/include +CFLAGSstreamutils= -c -std=c++11 -O3 -fPIC -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES -I. ############## LDFLAGSstreamutils = -shared -lrt -pthread LDFLAGSmdsutils = -shared -lrt -pthread -L$(MDSPLUS_DIR)/lib -lMdsObjectsCppShr -lMdsIpShr diff --git a/device_support/camera_utils/cammdsutils.cpp b/device_support/camera_utils/cammdsutils.cpp index 4923ed9ffb..b21d99c276 100644 --- a/device_support/camera_utils/cammdsutils.cpp +++ b/device_support/camera_utils/cammdsutils.cpp @@ -27,414 +27,558 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include using namespace MDSplus; #include "cammdsutils.h" + using namespace std; -// DEBUG mode if defined + +//DEBUG mode if defined //#define DEBUG -// Support class for enqueueing Frame storage requests -class SaveFrame -{ - void *frame; - int width; - int height; - int pixelSize; - int segmentSize; - int frameIdx; - int dataNid; - int timebaseNid; //-1 means no timebase - float frameTime; - void *treePtr; - - bool hasMetadata; - void *frameMetadata; - int metaSize; - int metaNid; - - SaveFrame *nxt; - -public: - SaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, - void *treePtr, int dataNid, int timebaseNid, int frameIdx, - void *frameMetadata, int metaSize, int metaNid) - { - this->frame = frame; - this->width = width; - this->height = height; - this->pixelSize = pixelSize; - this->segmentSize = segmentSize; - this->frameIdx = frameIdx; - this->dataNid = dataNid; - this->timebaseNid = timebaseNid; - this->frameTime = frameTime; - - hasMetadata = true; - this->frameMetadata = frameMetadata; - this->metaSize = metaSize; - this->metaNid = metaNid; - - this->treePtr = treePtr; - nxt = 0; - } - SaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, - void *treePtr, int dataNid, int timebaseNid, int frameIdx) - { - this->frame = frame; - this->width = width; - this->height = height; - this->pixelSize = pixelSize; - this->segmentSize = segmentSize; - this->frameIdx = frameIdx; - this->dataNid = dataNid; - this->timebaseNid = timebaseNid; - this->frameTime = frameTime; - - hasMetadata = false; - this->frameMetadata = 0; - this->metaSize = 0; - this->metaNid = -1; - - this->treePtr = treePtr; - nxt = 0; - } - - void setNext(SaveFrame *itm) { nxt = itm; } - - SaveFrame *getNext() { return nxt; } - - void save() - { - - int dataDims[] = {1, height, width}; - int metaDims[] = {1, metaSize}; - - TreeNode *dataNode = new TreeNode(dataNid, (Tree *)treePtr); - TreeNode *metaNode; - if (hasMetadata) - metaNode = new TreeNode(metaNid, (Tree *)treePtr); - TreeNode *tBase = new TreeNode(timebaseNid, (Tree *)treePtr); - - Data *data; - Data *metaData = 0; - if (hasMetadata) - metaData = new Int8Array((char *)frameMetadata, 2, metaDims); - - // check pixel size format - if (pixelSize <= 8) + +//Support class for enqueueing Frame storage requests +class SaveFrame { + + void *frame; + int width; + int height; + int pixelSize; + int segmentSize; + int frameIdx; + int dataNid; + int timebaseNid; //-1 means no timebase + float frameTime; + void *treePtr; + + bool hasMetadata; + void *frameMetadata; + int metaSize; + int metaNid; + + int pixelLevel; + int numPixel; + int discardBlackFrame = 0; + + SaveFrame *nxt; + + public: + SaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx, void *frameMetadata, int metaSize, int metaNid, + int pixelLevel, int numPixel) { - data = new Int8Array((char *)frame, 3, dataDims); -#ifdef DEBUG - printf("Pixel Format: 8bit.\n"); -#endif + this->frame = frame; + this->width = width; + this->height = height; + this->pixelSize = pixelSize; + this->segmentSize = segmentSize; + this->frameIdx = frameIdx; + this->dataNid = dataNid; + this->timebaseNid = timebaseNid; + this->frameTime = frameTime; + + hasMetadata = true; + this->frameMetadata = frameMetadata; + this->metaSize = metaSize; + this->metaNid = metaNid; + + this->treePtr = treePtr; + + if( pixelLevel > 0 && numPixel > 0 ) + { + this->pixelLevel = pixelLevel; + this->numPixel = numPixel; + this->discardBlackFrame = 1; + } + else + this->discardBlackFrame = 0; + + nxt = 0; } - else if (pixelSize <= 16) + SaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx) { - data = new Int16Array((short *)frame, 3, dataDims); -#ifdef DEBUG - printf("Pixel Format: 16bit. %d %d %d\n", dataDims[0], dataDims[1], - dataDims[2]); -#endif + this->frame = frame; + this->width = width; + this->height = height; + this->pixelSize = pixelSize; + this->segmentSize = segmentSize; + this->frameIdx = frameIdx; + this->dataNid = dataNid; + this->timebaseNid = timebaseNid; + this->frameTime = frameTime; + + hasMetadata = false; + this->frameMetadata = 0; + this->metaSize = 0; + this->metaNid = -1; + + discardBlackFrame = 0; + + this->treePtr = treePtr; + nxt = 0; + } + + void setNext(SaveFrame *itm) + { + nxt = itm; } - else if (pixelSize <= 32) + + SaveFrame *getNext() { - data = new Int32Array((int *)frame, 3, dataDims); -#ifdef DEBUG - printf("Pixel Format: 32bit.\n"); -#endif + return nxt; } - if (timebaseNid != -1) // timebase defined (ext. trigger) + + int isBlackFrame(int pixelLevel, int numPixel) { - TreeNode *timebaseNode; - Data *idxData; - Data *time; - Data *dim; - - try - { - timebaseNode = new TreeNode(timebaseNid, (Tree *)treePtr); -#ifdef DEBUG - printf("SAVE Frame IDX %d %s\n", frameIdx, dataNode->decompile()); -#endif - idxData = new Int32(frameIdx); - time = compileWithArgs("fs_float($1[$2])", (Tree *)treePtr, 2, - timebaseNode, idxData); - dim = compileWithArgs("fs_float([$1[$2]])", (Tree *)treePtr, 2, - timebaseNode, idxData); - dataNode->makeSegment(time, time, dim, (Array *)data); - if (hasMetadata && metaSize > 0) + int npixel = height * width; + int cntPixel = 0; + + if(pixelSize<=8) { - metaNode->makeSegment(time, time, dim, (Array *)metaData); + char *cframe = (char *) frame; + for(int i; i < npixel;i++) + if((int)cframe[i] > pixelLevel) + cntPixel++; + } else if(pixelSize<=16) { + short *sframe = (short *) frame; + for(int i; i < npixel;i++) + if((int)sframe[i] > pixelLevel) + cntPixel++; + } else if(pixelSize<=32) { + int *iframe = (int *) frame; + for(int i; i < npixel;i++) + if((int)iframe[i] > pixelLevel) + cntPixel++; } - } - catch (const MdsException &exc) - { - cout << "ERROR WRITING SEGMENT: " << exc.what() << "\n"; - } - deleteData(data); - deleteData(time); - deleteData(dim); - delete dataNode; - delete timebaseNode; - if (hasMetadata) - delete metaNode; - - if (pixelSize <= 8) - delete (char *)frame; - else if (pixelSize <= 16) - delete (short *)frame; - else if (pixelSize <= 32) - delete (int *)frame; + + return ( cntPixel > numPixel ? 0 : 1 ) ; } - else // timebase NOT defined (int. trigger) + + int save() { - Data *dim; - Data *time = new Float32(frameTime); - - try - { - dim = compileWithArgs("[$1]", (Tree *)treePtr, 1, time); - } - catch (const MdsException &exc) - { - cout << "ERROR CompileWithArgs: " << exc.what() << "\n"; - } - - try - { - // cout << "WRITING SEGMENT " << time << dim << data << " " << - // dataNode->getFullPath() <<"\n"; - - dataNode->makeSegment(time, time, dim, (Array *)data); - if (hasMetadata && metaSize > 0) + + int dataDims[] = {1, height, width}; + int metaDims[] = {1, metaSize}; + +/*Check black frame*/ + + if( discardBlackFrame && isBlackFrame( pixelLevel, numPixel) ) { - metaNode->makeSegment(time, time, dim, (Array *)metaData); + +printf("Is Black Frame.\n"); + + if(pixelSize<=8) + delete (char *) frame; + else if(pixelSize<=16) + delete (short *) frame; + else if(pixelSize<=32) + delete (int *) frame; + return 0; } - } - catch (const MdsException &exc) - { - cout << "ERROR WRITING SEGMENT " << exc.what() << "\n"; - } - - try - { - deleteData(data); - deleteData(time); - deleteData(dim); - delete dataNode; - if (hasMetadata) - delete metaNode; - - if (pixelSize <= 8) - delete (char *)frame; - else if (pixelSize <= 16) - delete (short *)frame; - else if (pixelSize <= 32) - delete (int *)frame; - } - catch (const MdsException &exc) - { - cout << "ERROR deleting data" << exc.what() << "\n"; - } - } - } +/*Fine chack*/ + + TreeNode *dataNode = new TreeNode(dataNid, (Tree *)treePtr); + TreeNode *metaNode; + if(hasMetadata) + metaNode = new TreeNode(metaNid, (Tree *)treePtr); + TreeNode *tBase = new TreeNode(timebaseNid, (Tree *)treePtr); + + Data *data; + Data *metaData = 0; + if(hasMetadata) + metaData = new Int8Array((char *)frameMetadata, 2, metaDims); + + //check pixel size format + if(pixelSize<=8) + { + data = new Int8Array((char *)frame, 3, dataDims); + #ifdef DEBUG + printf("Pixel Format: 8bit.\n"); + #endif + } + else if(pixelSize<=16) + { + data = new Int16Array((short *)frame, 3, dataDims); + #ifdef DEBUG + printf("Pixel Format: 16bit. %d %d %d\n", dataDims[0], dataDims[1], dataDims[2]); + #endif + } + else if(pixelSize<=32) + { + data = new Int32Array((int *)frame, 3, dataDims); + #ifdef DEBUG + printf("Pixel Format: 32bit.\n"); + #endif + } + + if(timebaseNid != -1) //timebase defined (ext. trigger) + { + TreeNode *timebaseNode; + Data *idxData; + Data *time; + Data *dim; + + try + { + timebaseNode = new TreeNode(timebaseNid, (Tree *)treePtr); + #ifdef DEBUG + printf("SAVE Frame IDX %d %s\n", frameIdx, dataNode->decompile()); + #endif + idxData = new Int32(frameIdx); + time = compileWithArgs("fs_float($1[$2])", (Tree *)treePtr, 2, timebaseNode, idxData); + dim = compileWithArgs("fs_float([$1[$2]])", (Tree *)treePtr, 2, timebaseNode, idxData); + dataNode->makeSegment(time, time, dim, (Array *)data); + if(hasMetadata && metaSize>0) + { + metaNode->makeSegment(time, time, dim, (Array *)metaData); + } + } + catch(MdsException *exc) + { + cout << "ERROR WRITING SEGMENT: " << exc->what() << "\n"; + } + deleteData(data); + deleteData(time); + deleteData(dim); + delete dataNode; + delete timebaseNode; + if(hasMetadata) delete metaNode; + + if(pixelSize<=8) + delete (char *) frame; + else if(pixelSize<=16) + delete (short *)frame; + else if(pixelSize<=32) + delete (int *) frame; + + } + else //timebase NOT defined (int. trigger) + { + Data *dim; + Data *time = new Float32(frameTime); + + try + { + dim = compileWithArgs("[$1]", (Tree *)treePtr, 1, time); + } + catch(MdsException *exc) + { + cout << "ERROR CompileWithArgs: " << exc->what() << "\n"; + } + + try + { + //cout << "WRITING SEGMENT " << time << dim << data << " " << dataNode->getFullPath() <<"\n"; + + dataNode->makeSegment(time, time, dim, (Array *)data); + if(hasMetadata && metaSize>0) + { + metaNode->makeSegment(time, time, dim, (Array *)metaData); + } + + } + catch(MdsException *exc) + { + cout << "ERROR WRITING SEGMENT " << exc->what() << "\n"; + } + + try + { + deleteData(data); + deleteData(time); + deleteData(dim); + delete dataNode; + if(hasMetadata) delete metaNode; + + if(pixelSize<=8) + delete (char *) frame; + else if(pixelSize<=16) + delete (short *)frame; + else if(pixelSize<=32) + delete (int *) frame; + } + catch(MdsException *exc) + { + cout << "ERROR deleting data" << exc->what() << "\n"; + } + } + return 1; + } }; class SaveFrameList { -public: - pthread_cond_t itemAvailable; - pthread_t thread; - bool threadCreated; - SaveFrame *saveHead, *saveTail; - bool stopReq; - bool deferredSave; - pthread_mutex_t mutex; - -public: - void setDeferredSave(bool deferredSave) { this->deferredSave = deferredSave; } - SaveFrameList() - { - int status = pthread_mutex_init(&mutex, NULL); - pthread_cond_init(&itemAvailable, NULL); - saveHead = saveTail = NULL; - stopReq = false; - deferredSave = false; - threadCreated = false; - } - - void addFrame(SaveFrame *newItem) - { - pthread_mutex_lock(&mutex); - if (saveHead == NULL) + public: + pthread_cond_t itemAvailable; + pthread_t thread; + bool threadCreated; + SaveFrame *saveHead, *saveTail; + bool stopReq; + bool deferredSave; + pthread_mutex_t mutex; + + int pixelLevel; + int numPixel; + + int savedFrame = 0; + int blackFrame = 0; + + + public: + void setDeferredSave(bool deferredSave) { - saveHead = saveTail = newItem; + this->deferredSave = deferredSave; } - else + + int getSavedFrame() { - saveTail->setNext(newItem); - saveTail = newItem; + return this->savedFrame; } - pthread_cond_signal(&itemAvailable); - pthread_mutex_unlock(&mutex); - } - - void addFrame(void *frame, int width, int height, float frameTime, - int pixelSize, void *treePtr, int dataNid, int timebaseNid, - int frameIdx, void *frameMetadata, int metaSize, int metaNid) - { - SaveFrame *newItem = new SaveFrame( - frame, width, height, frameTime, pixelSize, treePtr, dataNid, - timebaseNid, frameIdx, frameMetadata, metaSize, metaNid); - addFrame(newItem); - } - - void addFrame(void *frame, int width, int height, float frameTime, - int pixelSize, void *treePtr, int dataNid, int timebaseNid, - int frameIdx) - { - SaveFrame *newItem = - new SaveFrame(frame, width, height, frameTime, pixelSize, treePtr, - dataNid, timebaseNid, frameIdx); - addFrame(newItem); - } - - void executeItems() - { - while (true) + + int getBlackFrame() { - pthread_mutex_lock(&mutex); - if (stopReq && saveHead == NULL) - { - pthread_mutex_unlock(&mutex); - pthread_exit(NULL); - } - if (deferredSave) - { - pthread_cond_wait(&itemAvailable, &mutex); - if (!stopReq) - { - pthread_mutex_unlock(&mutex); - continue; - } - else + return this->blackFrame; + } + + SaveFrameList() + { + int status = pthread_mutex_init(&mutex, NULL); + pthread_cond_init(&itemAvailable, NULL); + saveHead = saveTail = NULL; + stopReq = false; + deferredSave = false; + threadCreated = false; + + savedFrame = 0; + blackFrame = 0; + + try { - // Empty pending queue - while (saveHead) - { - SaveFrame *currItem = saveHead; - saveHead = saveHead->getNext(); + char* val = std::getenv("BASLER_PIX_LEVEL"); + if( val != NULL && strlen(val) > 0 ) + pixelLevel = std::stoi(val); + else + pixelLevel = -1; + + val = std::getenv("BASLER_PIX_NUM"); + if( val != NULL && strlen(val) > 0 ) + numPixel = std::stoi(val); + else + numPixel = -1; + + if( pixelLevel > 0 && numPixel > 0 ) + printf("Black frame detection active with pixel level %d and number of pixel %d\n", pixelLevel, numPixel); + } + catch ( std::exception const & e ) + { + pixelLevel = -1; + numPixel = -1; + std::cout<<"error : " << e.what() << std::endl; + } + + } + + void addFrame(SaveFrame *newItem) + { + pthread_mutex_lock(&mutex); + if(saveHead == NULL) + { + saveHead = saveTail = newItem; + } + else + { + saveTail->setNext(newItem); + saveTail = newItem; + } + pthread_cond_signal(&itemAvailable); + pthread_mutex_unlock(&mutex); + + } + + void addFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, + int frameIdx, void *frameMetadata, int metaSize, int metaNid) + { + SaveFrame *newItem = new SaveFrame(frame, width, height, frameTime, pixelSize, treePtr, dataNid, timebaseNid, frameIdx, + frameMetadata, metaSize, metaNid, pixelLevel, numPixel); + addFrame(newItem); + } + + void addFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, + int frameIdx) + { + SaveFrame *newItem = new SaveFrame(frame, width, height, frameTime, pixelSize, treePtr, dataNid, timebaseNid, frameIdx); + addFrame(newItem); + } + + + + void executeItems() + { + while(true) + { + pthread_mutex_lock(&mutex); + if(stopReq && saveHead == NULL) + { + pthread_mutex_unlock(&mutex); + pthread_exit(NULL); + } + + if(deferredSave) + { + pthread_cond_wait(&itemAvailable, &mutex); + if(!stopReq) + { + pthread_mutex_unlock(&mutex); + continue; + } + else + { + //Empty pending queue + while(saveHead) + { + SaveFrame *currItem = saveHead; + saveHead = saveHead->getNext(); #ifdef DEBUG - int nItems = 0; - for (SaveFrame *itm = saveHead; itm; itm = itm->getNext(), nItems++) - ; - if (nItems > 0 && (nItems % 20) == 0) - printf("THREAD ACTIVATED: %d store frame items pending\n", - nItems); + int nItems = 0; + for(SaveFrame *itm = saveHead; itm; itm = itm->getNext(), nItems++); + if( nItems > 0 && (nItems % 20 ) == 0 ) printf("THREAD ACTIVATED: %d store frame items pending\n", nItems); #endif - currItem->save(); - delete currItem; - } - pthread_mutex_unlock(&mutex); - pthread_exit(NULL); - } - } - - while (saveHead == NULL) - { - pthread_cond_wait(&itemAvailable, &mutex); - if (stopReq && saveHead == NULL) - { - pthread_mutex_unlock(&mutex); - pthread_exit(NULL); - } - } - SaveFrame *currItem = saveHead; - saveHead = saveHead->getNext(); + if ( currItem->save() ) + savedFrame += 1; + else + blackFrame += 1; + + delete currItem; + } + pthread_mutex_unlock(&mutex); + pthread_exit(NULL); + } + } + + while(saveHead == NULL) + { + pthread_cond_wait(&itemAvailable, &mutex); + if(stopReq && saveHead == NULL) + { + pthread_mutex_unlock(&mutex); + pthread_exit(NULL); + } + } + SaveFrame *currItem = saveHead; + saveHead = saveHead->getNext(); #ifdef DEBUG - int nItems = 0; - for (SaveFrame *itm = saveHead; itm; itm = itm->getNext(), nItems++) - ; - if (nItems > 0 && (nItems % 20) == 0) - printf("THREAD ACTIVATED: %d store frame items pending\n", nItems); + int nItems = 0; + for(SaveFrame *itm = saveHead; itm; itm = itm->getNext(), nItems++); + if( nItems > 0 && (nItems % 20 ) == 0 ) printf("THREAD ACTIVATED: %d store frame items pending\n", nItems); #endif - pthread_mutex_unlock(&mutex); - currItem->save(); - delete currItem; + pthread_mutex_unlock(&mutex); + + if ( currItem->save() ) + savedFrame += 1; + else + blackFrame += 1; + + delete currItem; + } } - } - void start() - { - pthread_create(&thread, NULL, handleSave, (void *)this); - threadCreated = true; - } - void stop() - { - stopReq = true; - pthread_cond_signal(&itemAvailable); - if (threadCreated) + + void start() + { + pthread_create(&thread, NULL, handleSave, (void *)this); + threadCreated = true; + } + + void stop() { - pthread_join(thread, NULL); + stopReq = true; + pthread_cond_signal(&itemAvailable); + if(threadCreated) + { + pthread_join(thread, NULL); #ifdef DEBUG - printf("SAVE THREAD TERMINATED\n"); + printf("SAVE THREAD TERMINATED\n"); #endif + } } - } -}; + }; + static void *handleSave(void *listPtr) { - SaveFrameList *list = (SaveFrameList *)listPtr; - list->executeItems(); - return NULL; + SaveFrameList *list = (SaveFrameList *)listPtr; + list->executeItems(); + return NULL; } void camStartSave(void **retList) { - SaveFrameList *saveFrameList = new SaveFrameList; - saveFrameList->start(); - *retList = (void *)saveFrameList; + SaveFrameList *saveFrameList = new SaveFrameList; + saveFrameList->start(); + *retList = (void *)saveFrameList; } void camStartSaveDeferred(void **retList) { - SaveFrameList *saveFrameList = new SaveFrameList; - saveFrameList->setDeferredSave(true); - saveFrameList->start(); - *retList = (void *)saveFrameList; + SaveFrameList *saveFrameList = new SaveFrameList; + saveFrameList->setDeferredSave(true); + saveFrameList->start(); + *retList = (void *)saveFrameList; } +int camSavedFrame(void *listPtr) +{ + if(listPtr) + { + return ((SaveFrameList *)listPtr)->getSavedFrame(); + } + return 0; +} + +int camBlackFrame(void *listPtr) +{ + if(listPtr) + { + return ((SaveFrameList *)listPtr)->getBlackFrame(); + } + return 0; +} + + void camStopSave(void *listPtr) { - if (listPtr) - { - SaveFrameList *list = (SaveFrameList *)listPtr; - list->stop(); - delete list; - } + if(listPtr) + { + SaveFrameList *list = (SaveFrameList *)listPtr; + list->stop(); + delete list; + } } -// Open Mdsplus Tree + +//Open Mdsplus Tree int camOpenTree(char *treeName, int shot, void **treePtr) { - try - { - Tree *tree = new Tree(treeName, shot); - *treePtr = (void *)tree; - return 0; - } - catch (const MdsException &exc) - { - cout << "Error opening Tree " << treeName << ": " << exc.what() << "\n"; - return -1; - } + try + { + Tree *tree = new Tree(treeName, shot); + *treePtr = (void *)tree; + return 0; + }catch(MdsException *exc) + { + cout << "Error opening Tree " << treeName << ": " << exc->what() << "\n"; + return -1; + } } -// Close Mdsplus Tree -int camCloseTree(void *treePtr) { delete (Tree *)treePtr; } + +//Close Mdsplus Tree +int camCloseTree(void *treePtr) +{ + delete (Tree *)treePtr; +} + + /* Save 1 frame in mdsplus @@ -453,65 +597,62 @@ int metaSize metadata size int metaNid MdsPlus NodeID for the metadata */ -void camSaveFrame(void *frame, int width, int height, float frameTime, - int pixelSize, void *treePtr, int dataNid, int timebaseNid, - int frameIdx, void *frameMetadata, int metaSize, int metaNid, - void *saveListPtr) +void camSaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx, + void *frameMetadata, int metaSize, int metaNid, void *saveListPtr) { - void *bufFrame; - void *bufMdata; - int frameSize = width * height; - - if (pixelSize <= 8) - { - bufFrame = new char[frameSize]; - memcpy(bufFrame, frame, frameSize * sizeof(char)); - } - else if (pixelSize <= 16) - { - bufFrame = new short[frameSize]; - memcpy(bufFrame, frame, frameSize * sizeof(short)); - } - else if (pixelSize <= 32) - { - bufFrame = new int[frameSize]; - memcpy(bufFrame, frame, frameSize * sizeof(int)); - } - - bufMdata = new char[metaSize]; - memcpy(bufMdata, frameMetadata, metaSize); - - SaveFrameList *saveList = (SaveFrameList *)saveListPtr; - saveList->addFrame(bufFrame, width, height, frameTime, pixelSize, treePtr, - dataNid, timebaseNid, frameIdx, bufMdata, metaSize, - metaNid); + void *bufFrame; + void *bufMdata; + int frameSize = width * height; + + if(pixelSize<=8) + { + bufFrame = new char[frameSize]; + memcpy(bufFrame, frame, frameSize * sizeof(char)); + } + else if(pixelSize<=16) + { + bufFrame = new short[frameSize]; + memcpy(bufFrame, frame, frameSize * sizeof(short)); + } + else if(pixelSize<=32) + { + bufFrame = new int[frameSize]; + memcpy(bufFrame, frame, frameSize * sizeof(int)); + } + + bufMdata = new char[metaSize]; + memcpy(bufMdata, frameMetadata, metaSize); + + SaveFrameList *saveList = (SaveFrameList *)saveListPtr; + saveList->addFrame(bufFrame, width, height, frameTime, pixelSize, treePtr, dataNid, timebaseNid, frameIdx, bufMdata, metaSize, metaNid); + } -void camSaveFrameDirect(void *frame, int width, int height, float frameTime, - int pixelSize, void *treePtr, int dataNid, - int timebaseNid, int frameIdx, void *saveListPtr) +void camSaveFrameDirect(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, + int frameIdx, void *saveListPtr) { - void *bufFrame; - int frameSize = width * height; - if (pixelSize <= 8) - { - bufFrame = new char[frameSize]; - memcpy(bufFrame, frame, frameSize * sizeof(char)); - } - else if (pixelSize <= 16) - { - bufFrame = new short[frameSize]; - memcpy(bufFrame, frame, frameSize * sizeof(short)); - } - else if (pixelSize <= 32) - { - bufFrame = new int[frameSize]; - memcpy(bufFrame, frame, frameSize * sizeof(int)); - } - - SaveFrameList *saveList = (SaveFrameList *)saveListPtr; - saveList->addFrame(bufFrame, width, height, frameTime, pixelSize, treePtr, - dataNid, timebaseNid, frameIdx); + void *bufFrame; + int frameSize = width * height; + if(pixelSize<=8) + { + bufFrame = new char[frameSize]; + memcpy(bufFrame, frame, frameSize * sizeof(char)); + } + else if(pixelSize<=16) + { + bufFrame = new short[frameSize]; + memcpy(bufFrame, frame, frameSize * sizeof(short)); + } + else if(pixelSize<=32) + { + bufFrame = new int[frameSize]; + memcpy(bufFrame, frame, frameSize * sizeof(int)); + } + + SaveFrameList *saveList = (SaveFrameList *)saveListPtr; + saveList->addFrame(bufFrame, width, height, frameTime, pixelSize, treePtr, dataNid, timebaseNid, frameIdx); } + + diff --git a/device_support/camera_utils/cammdsutils.h b/device_support/camera_utils/cammdsutils.h index 8228b929c9..8350b6adaf 100644 --- a/device_support/camera_utils/cammdsutils.h +++ b/device_support/camera_utils/cammdsutils.h @@ -1,26 +1,23 @@ #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - int camOpenTree(char *treeName, int shot, void **treePtr); - int camCloseTree(void *treePtr); - // int camSaveFrame(void *frame, int width, int height, float frameTime, int - // pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx, void - // *frameMetadata, int metaSize, int metaNid); - void camSaveFrame(void *frame, int width, int height, float frameTime, - int pixelSize, void *treePtr, int dataNid, int timebaseNid, - int frameIdx, void *frameMetadata, int metaSize, int metaNid, - void *saveListPtr); - void camSaveFrameDirect(void *frame, int width, int height, float frameTime, - int pixelSize, void *treePtr, int dataNid, - int timebaseNid, int frameIdx, void *saveListPtr); +int camOpenTree(char *treeName, int shot, void **treePtr); +int camCloseTree(void *treePtr); +//int camSaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx, void *frameMetadata, int metaSize, int metaNid); +void camSaveFrame(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, int frameIdx, void *frameMetadata, int metaSize, int metaNid, void *saveListPtr); +void camSaveFrameDirect(void *frame, int width, int height, float frameTime, int pixelSize, void *treePtr, int dataNid, int timebaseNid, + int frameIdx, void *saveListPtr); - static void *handleSave(void *listPtr); - void camStartSaveDeferred(void **retList); - void camStartSave(void **retList); - void camStopSave(void *listPtr); +static void *handleSave(void *listPtr); +void camStartSaveDeferred(void **retList); +void camStartSave(void **retList); +void camStopSave(void *listPtr); + +int camSavedFrame(void *listPtr); +int camBlackFrame(void *listPtr); #ifdef __cplusplus } #endif + diff --git a/device_support/camera_utils/camstreamutils.cpp b/device_support/camera_utils/camstreamutils.cpp index f13fa36441..cc1d4c302f 100644 --- a/device_support/camera_utils/camstreamutils.cpp +++ b/device_support/camera_utils/camstreamutils.cpp @@ -28,317 +28,289 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include using namespace std; #include -// TCP SENDER + +//TCP SENDER #include #include #include #include #include -#include //tcp error enumeration +#include //tcp error enumeration -// FFMPEG TEXT OVERLAY +//FFMPEG TEXT OVERLAY #include #include -#include //temp 4 debug +#include //temp 4 debug #include "camstreamutils.h" -// debug mode if defined +//debug mode if defined //#define debug -// support to get the pixel size of the selected pixel format. -int getPixelSize( - int pixelFormat) // return the number of bit used for the format + +//support to get the pixel size of the selected pixel format. +int getPixelSize(int pixelFormat) //return the number of bit used for the format { - if (pixelFormat == CSU_PIX_FMT_NONE) - return 0; - if (pixelFormat == CSU_PIX_FMT_GRAY8) - return 8; - if (pixelFormat == CSU_PIX_FMT_GRAY16) - return 16; - if (pixelFormat == CSU_PIX_FMT_BAYER_RGGB8) - return 8; - if (pixelFormat == CSU_PIX_FMT_YUV422_Packed) - return 16; + if(pixelFormat==CSU_PIX_FMT_NONE) + return 0; + if(pixelFormat==CSU_PIX_FMT_GRAY8) + return 8; + if(pixelFormat==CSU_PIX_FMT_GRAY16) + return 16; + if(pixelFormat==CSU_PIX_FMT_BAYER_RGGB8) + return 8; + if(pixelFormat==CSU_PIX_FMT_YUV422_Packed) + return 16; } -// Support class for enqueueing Frame streaming requests -class StreamingFrame -{ - void *frame; - int width; - int height; - int pixelSize; - int pixelFormat; // according to GENICAM Pixel Format Naming Convention - // (PFNC 2.1) - int irFrameFormat; - bool adjLimit; - unsigned int *lowLim; - unsigned int *highLim; - unsigned int minLim; - unsigned int maxLim; - int adjRoiX; - int adjRoiY; - int adjRoiW; - int adjRoiH; - int tcpStreamHandle; - const char *deviceName; - - StreamingFrame *nxt; - -public: - StreamingFrame(int tcpStreamHandle, void *frame, int width, int height, - int pixelFormat, int irFrameFormat, bool adjLimit, - unsigned int *lowLim, unsigned int *highLim, - unsigned int minLim, unsigned int maxLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName) - { - this->tcpStreamHandle = tcpStreamHandle; - this->frame = frame; - this->width = width; - this->height = height; - this->pixelSize = getPixelSize(pixelFormat); - this->pixelFormat = pixelFormat; - this->irFrameFormat = irFrameFormat; - this->adjLimit = adjLimit; - this->lowLim = lowLim; - this->highLim = highLim; - this->minLim = minLim; - this->maxLim = maxLim; - this->adjRoiX = adjRoiX; - this->adjRoiY = adjRoiY; - this->adjRoiW = adjRoiW; - this->adjRoiH = adjRoiH; - this->deviceName = deviceName; - - nxt = 0; - } +//Support class for enqueueing Frame streaming requests +class StreamingFrame { + + void *frame; + int width; + int height; + int pixelSize; + int pixelFormat; //according to GENICAM Pixel Format Naming Convention (PFNC 2.1) + int irFrameFormat; + bool adjLimit; + unsigned int *lowLim; + unsigned int *highLim; + unsigned int minLim; + unsigned int maxLim; + int adjRoiX; + int adjRoiY; + int adjRoiW; + int adjRoiH; + int tcpStreamHandle; + const char *deviceName; + + StreamingFrame *nxt; + + public: + StreamingFrame(int tcpStreamHandle, void *frame, int width, int height, int pixelFormat, int irFrameFormat, bool adjLimit, unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) + { + this->tcpStreamHandle = tcpStreamHandle; + this->frame = frame; + this->width = width; + this->height = height; + this->pixelSize = getPixelSize(pixelFormat); + this->pixelFormat = pixelFormat; + this->irFrameFormat = irFrameFormat; + this->adjLimit = adjLimit; + this->lowLim = lowLim; + this->highLim = highLim; + this->minLim = minLim; + this->maxLim = maxLim; + this->adjRoiX = adjRoiX; + this->adjRoiY = adjRoiY; + this->adjRoiW = adjRoiW; + this->adjRoiH = adjRoiH; + this->deviceName = deviceName; + + nxt = 0; + } - void setNext(StreamingFrame *itm) { nxt = itm; } + void setNext(StreamingFrame *itm) + { + nxt = itm; + } - StreamingFrame *getNext() { return nxt; } + StreamingFrame *getNext() + { + return nxt; + } - void streaming() - { - unsigned char *frame8bit = - (unsigned char *)calloc(1, width * height * sizeof(char)); - camFrameTo8bit(frame, width, height, pixelFormat, frame8bit, adjLimit, - lowLim, highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, - adjRoiH); - - struct tm *tm; // date & time used in FFMPEG_OVERLAY_***DEVICE-NAME*** file - time_t t; - char str_datetime[25]; - t = time(NULL); - tm = localtime(&t); - strcpy(str_datetime, ""); - strftime(str_datetime, sizeof(str_datetime), "%d-%m-%Y %H:%M:%S", tm); - - char textString[100]; - sprintf(textString, "%s\n%s\nMin.:%d Max.:%d", this->deviceName, - str_datetime, *lowLim, - *highLim); // text overlay example: IRCAM01 - 2017-02-06 10:08:00 - - // Min.:10 Max.:50 - - char filename[40]; - sprintf(filename, "FFMPEG_OVERLAY_%s.txt", this->deviceName); - - camFFMPEGoverlay(filename, textString); - - camSendFrameOnTcp(&tcpStreamHandle, width, height, frame8bit); - free(frame8bit); - - if (pixelSize <= 8) - delete (char *)frame; - else if (pixelSize <= 16) - delete (short *)frame; - else if (pixelSize <= 32) - delete (int *)frame; - } + void streaming() + { + unsigned char *frame8bit = (unsigned char *) calloc(1, width * height * sizeof(char)); + camFrameTo8bit(frame, width, height, pixelFormat, frame8bit, adjLimit, lowLim, highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH); + + struct tm *tm; //date & time used in FFMPEG_OVERLAY_***DEVICE-NAME*** file + time_t t; + char str_datetime[25]; + t = time(NULL); + tm = localtime(&t); + strcpy(str_datetime,""); + strftime(str_datetime, sizeof(str_datetime), "%d-%m-%Y %H:%M:%S", tm); + + char textString[100]; + sprintf(textString, "%s\n%s\nMin.:%d Max.:%d",this->deviceName, str_datetime, *lowLim, *highLim); //text overlay example: IRCAM01 - 2017-02-06 10:08:00 - Min.:10 Max.:50 + + char filename[40]; + sprintf(filename, "FFMPEG_OVERLAY_%s.txt", this->deviceName); + + camFFMPEGoverlay(filename, textString); + + camSendFrameOnTcp(&tcpStreamHandle, width, height, frame8bit); + free(frame8bit); + + if(pixelSize<=8) + delete (char *) frame; + else if(pixelSize<=16) + delete (short *)frame; + else if(pixelSize<=32) + delete (int *) frame; + } }; class StreamingFrameList { -public: - pthread_cond_t itemAvailable; - pthread_t thread; - bool threadCreated; - StreamingFrame *streamingHead, *streamingTail; - bool stopReq; - pthread_mutex_t mutex; - -public: - StreamingFrameList() - { - int status = pthread_mutex_init(&mutex, NULL); - pthread_cond_init(&itemAvailable, NULL); - streamingHead = streamingTail = NULL; - stopReq = false; - threadCreated = false; - } - - void addStreamingFrame(int tcpStreamHandle, void *frame, int width, - int height, int pixelFormat, int irFrameFormat, - bool adjLimit, unsigned int *lowLim, - unsigned int *highLim, unsigned int minLim, - unsigned int maxLim, int adjRoiX, int adjRoiY, - int adjRoiW, int adjRoiH, const char *deviceName) - { - // printf("add streaming frame\n"); - StreamingFrame *newItem = new StreamingFrame( - tcpStreamHandle, frame, width, height, pixelFormat, irFrameFormat, - adjLimit, lowLim, highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, - adjRoiH, deviceName); - pthread_mutex_lock(&mutex); - if (streamingHead == NULL) + public: + pthread_cond_t itemAvailable; + pthread_t thread; + bool threadCreated; + StreamingFrame *streamingHead, *streamingTail; + bool stopReq; + pthread_mutex_t mutex; + public: + + StreamingFrameList() { - streamingHead = streamingTail = newItem; + int status = pthread_mutex_init(&mutex, NULL); + pthread_cond_init(&itemAvailable, NULL); + streamingHead = streamingTail = NULL; + stopReq = false; + threadCreated = false; } - else + + void addStreamingFrame(int tcpStreamHandle, void *frame, int width, int height, int pixelFormat, int irFrameFormat, bool adjLimit, unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) { - streamingTail->setNext(newItem); - streamingTail = newItem; + //printf("add streaming frame\n"); + StreamingFrame *newItem = new StreamingFrame(tcpStreamHandle, frame, width, height, pixelFormat, irFrameFormat, adjLimit, lowLim, highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); + pthread_mutex_lock(&mutex); + if(streamingHead == NULL) + { + streamingHead = streamingTail = newItem; + } + else + { + streamingTail->setNext(newItem); + streamingTail = newItem; + } + pthread_cond_signal(&itemAvailable); + pthread_mutex_unlock(&mutex); } - pthread_cond_signal(&itemAvailable); - pthread_mutex_unlock(&mutex); - } - void executeItems() - { - while (true) - { - if (stopReq && streamingHead == NULL) - { - pthread_mutex_destroy(&mutex); - pthread_exit(NULL); - } - - while (streamingHead == NULL) - { - if (stopReq && streamingHead == NULL) - { - pthread_mutex_destroy(&mutex); - pthread_exit(NULL); - } - int nItems = 0; - for (StreamingFrame *itm = streamingHead; itm; - itm = itm->getNext(), nItems++) - ; - // if(nItems > 2) printf("THREAD ACTIVATED: %d streaming items - // pending\n", nItems); - - if (nItems > 0 && (nItems % 20) == 0) - printf("THREAD ACTIVATED NULL HEAD: %d streaming items pending\n", - nItems); - // printf("Streaming buffer queue empty...\n"); - } - pthread_mutex_lock(&mutex); - StreamingFrame *currItem = streamingHead; - streamingHead = streamingHead->getNext(); - pthread_mutex_unlock(&mutex); - int nItems = 0; - for (StreamingFrame *itm = streamingHead; itm; - itm = itm->getNext(), nItems++) - ; - if (nItems > 2) - printf("THREAD ACTIVATED: %d streaming items pending\n", nItems); - if (nItems > 0 && (nItems % 20) == 0) - printf("THREAD ACTIVATED: %d streaming items pending\n", nItems); - - currItem->streaming(); - delete currItem; - usleep(10000); // 10ms - // printf("end usleep\n"); + void executeItems() + { + while(true) + { + if(stopReq && streamingHead == NULL) + { + pthread_mutex_destroy(&mutex); + pthread_exit(NULL); + } + + while(streamingHead == NULL) + { + if(stopReq && streamingHead == NULL) + { + pthread_mutex_destroy(&mutex); + pthread_exit(NULL); + } + + int nItems = 0; + for(StreamingFrame *itm = streamingHead; itm; itm = itm->getNext(), nItems++); + //if(nItems > 2) printf("THREAD ACTIVATED: %d streaming items pending\n", nItems); + + if(nItems > 0 && (nItems % 20 ) == 0) printf("THREAD ACTIVATED NULL HEAD: %d streaming items pending\n", nItems); + //printf("Streaming buffer queue empty...\n"); + + usleep(10000); //10ms + } + pthread_mutex_lock(&mutex); + StreamingFrame *currItem = streamingHead; + streamingHead = streamingHead->getNext(); + pthread_mutex_unlock(&mutex); + int nItems = 0; + for(StreamingFrame *itm = streamingHead; itm; itm = itm->getNext(), nItems++); + if(nItems > 2) printf("THREAD ACTIVATED: %d streaming items pending\n", nItems); + if(nItems > 0 && (nItems % 20 ) == 0) printf("THREAD ACTIVATED: %d streaming items pending\n", nItems); + + currItem->streaming(); + delete currItem; + usleep(10000); //10ms + //printf("end usleep\n"); + } } - } - void start() - { - pthread_create(&thread, NULL, handleStreaming, (void *)this); - threadCreated = true; - } + void start() + { + pthread_create(&thread, NULL, handleStreaming, (void *)this); + threadCreated = true; + } - void stop() - { - stopReq = true; - pthread_cond_signal(&itemAvailable); - if (threadCreated) + void stop() { - pthread_join(thread, NULL); - printf("Streaming THREAD TERMINATED\n"); + stopReq = true; + pthread_cond_signal(&itemAvailable); + if(threadCreated) + { + pthread_join(thread, NULL); + printf("Streaming THREAD TERMINATED\n"); + } } - } }; + void *handleStreaming(void *listPtr) { - StreamingFrameList *list = (StreamingFrameList *)listPtr; - list->executeItems(); - return NULL; + StreamingFrameList *list = (StreamingFrameList *)listPtr; + list->executeItems(); + return NULL; } void camStartStreaming(void **retList) { - StreamingFrameList *streamingFrameList = new StreamingFrameList; - streamingFrameList->start(); - *retList = (void *)streamingFrameList; + StreamingFrameList *streamingFrameList = new StreamingFrameList; + streamingFrameList->start(); + *retList = (void *)streamingFrameList; } void camStopStreaming(void *listPtr) { - if (listPtr) - { - StreamingFrameList *list = (StreamingFrameList *)listPtr; - list->stop(); - delete list; - } + if(listPtr) + { + StreamingFrameList *list = (StreamingFrameList *)listPtr; + list->stop(); + delete list; + } } -void camStreamingFrame(int tcpStreamHandle, void *frame, int width, int height, - int pixelFormat, int irFrameFormat, bool adjLimit, - unsigned int *lowLim, unsigned int *highLim, - unsigned int minLim, unsigned int maxLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName, void *streamingListPtr) +void camStreamingFrame(int tcpStreamHandle, void *frame, int width, int height, int pixelFormat, int irFrameFormat, bool adjLimit, unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName, void *streamingListPtr) { - void *bufFrame; + void *bufFrame; - int pixelSize = getPixelSize(pixelFormat); - int frameSize = width * height; + int pixelSize = getPixelSize(pixelFormat); + int frameSize = width * height; - if (pixelSize <= 8) - { - bufFrame = new char[frameSize]; - memcpy(bufFrame, frame, frameSize * sizeof(char)); - } - else if (pixelSize <= 16) - { - bufFrame = new short[frameSize]; - memcpy(bufFrame, frame, frameSize * sizeof(short)); - } - else if (pixelSize <= 32) - { - bufFrame = new int[frameSize]; - memcpy(bufFrame, frame, frameSize * sizeof(int)); - } + if(pixelSize<=8) + { + bufFrame = new char[frameSize]; + memcpy(bufFrame, frame, frameSize * sizeof(char)); + } + else if(pixelSize<=16) + { + bufFrame = new short[frameSize]; + memcpy(bufFrame, frame, frameSize * sizeof(short)); + } + else if(pixelSize<=32) + { + bufFrame = new int[frameSize]; + memcpy(bufFrame, frame, frameSize * sizeof(int)); + } - StreamingFrameList *streamingList = (StreamingFrameList *)streamingListPtr; - streamingList->addStreamingFrame(tcpStreamHandle, bufFrame, width, height, - pixelFormat, irFrameFormat, adjLimit, lowLim, - highLim, minLim, maxLim, adjRoiX, adjRoiY, - adjRoiW, adjRoiH, deviceName); + StreamingFrameList *streamingList = (StreamingFrameList *)streamingListPtr; + streamingList->addStreamingFrame(tcpStreamHandle, bufFrame, width, height, pixelFormat, irFrameFormat, adjLimit, lowLim, highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); } + //*********************************************** -/*open TCP connection (localhost on specified StreamingPort) and init streaming - * (connection to FFMPEG)*/ -int camOpenTcpConnection(const char *streamingServer, int StreamingPort, - int *kSockHandle, int width, int height, - int pixelFormat) +/*open TCP connection (localhost on specified StreamingPort) and init streaming (connection to FFMPEG)*/ +int camOpenTcpConnection(const char *streamingServer, int StreamingPort, int *kSockHandle, int width, int height, int pixelFormat) { struct sockaddr_in sin; struct hostent *hp; @@ -347,67 +319,68 @@ int camOpenTcpConnection(const char *streamingServer, int StreamingPort, cout << "Open TCP connection..." << endl; #endif - /* Resolve the passed name and store the resulting long representation in the - * struct hostent variable */ +/* Resolve the passed name and store the resulting long representation in the struct hostent variable */ if ((hp = gethostbyname(streamingServer)) == 0) { - // perror("gethostbyname"); + //perror("gethostbyname"); return -1; } - /* fill in the socket structure with host information */ +/* fill in the socket structure with host information */ memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr; sin.sin_port = htons(StreamingPort); - /* create a new socket */ - if (*kSockHandle == -1) - { +/* create a new socket */ + if(*kSockHandle==-1) + { if ((*kSockHandle = socket(AF_INET, SOCK_STREAM, 0)) == -1) { - // perror("socket"); + //perror("socket"); return -1; } } - // 20170615 fede new - int n; - unsigned int m = sizeof(n); - getsockopt(*kSockHandle, SOL_SOCKET, SO_RCVBUF, (void *)&n, &m); // SO_RCVBUF - printf("Buffer Receive size in bytes: %d\n", n); - getsockopt(*kSockHandle, SOL_SOCKET, SO_SNDBUF, (void *)&n, &m); // SO_RCVBUF - printf("Buffer Send size in bytes: %d\n", n); + +//20170615 fede new + int n; + unsigned int m = sizeof(n); + + getsockopt(*kSockHandle,SOL_SOCKET,SO_RCVBUF,(void *)&n, &m); //SO_RCVBUF + printf("Buffer Receive size in bytes: %d\n", n); + getsockopt(*kSockHandle,SOL_SOCKET,SO_SNDBUF,(void *)&n, &m); //SO_RCVBUF + printf("Buffer Send size in bytes: %d\n", n); // where socketfd is the socket you want to make non-blocking - /* - int status = fcntl(*kSockHandle, F_SETFL, fcntl(*kSockHandle, F_GETFL, 0) | - O_NONBLOCK); if (status == -1){ printf("calling fcntl");// handle the error. - By the way, I've never seen fcntl fail in this way - } +/* + int status = fcntl(*kSockHandle, F_SETFL, fcntl(*kSockHandle, F_GETFL, 0) | O_NONBLOCK); + if (status == -1){ + printf("calling fcntl");// handle the error. By the way, I've never seen fcntl fail in this way + } - int newMaxBuff=512000; - setsockopt(*kSockHandle, SOL_SOCKET, SO_SNDBUF, &newMaxBuff, - sizeof(newMaxBuff)); + int newMaxBuff=512000; + setsockopt(*kSockHandle, SOL_SOCKET, SO_SNDBUF, &newMaxBuff, sizeof(newMaxBuff)); - int flags = fcntl(*kSockHandle, F_GETFD); - if ((flags & O_NONBLOCK) == O_NONBLOCK) { - printf("Yup, it's nonblocking"); - } - else { - printf("Nope, it's blocking."); - } - */ - // 20170615 fede end new + int flags = fcntl(*kSockHandle, F_GETFD); + if ((flags & O_NONBLOCK) == O_NONBLOCK) { + printf("Yup, it's nonblocking"); + } + else { + printf("Nope, it's blocking."); + } +*/ +//20170615 fede end new - /* connect the socket to the port and host specified in struct sockaddr_in */ - if (connect(*kSockHandle, (struct sockaddr *)&sin, sizeof(sin)) == -1) + +/* connect the socket to the port and host specified in struct sockaddr_in */ + if (connect(*kSockHandle,(struct sockaddr *)&sin, sizeof(sin)) == -1) { - // perror("connect"); - // char lDoodle[] = "-+*"; - // printf("%c Error: connection refused!\r", lDoodle[rand()%3]); - // cout << "kSockHandle: " << *kSockHandle << endl; + //perror("connect"); + //char lDoodle[] = "-+*"; + //printf("%c Error: connection refused!\r", lDoodle[rand()%3]); + //cout << "kSockHandle: " << *kSockHandle << endl; return -1; } @@ -420,270 +393,262 @@ int camOpenTcpConnection(const char *streamingServer, int StreamingPort, int netPixelFormat = htonl(pixelFormat); /* init frame size streaming */ - if (send(*kSockHandle, &netWidth, sizeof(netWidth), 0) == -1) + if(send(*kSockHandle, &netWidth, sizeof(netWidth), 0) == -1) { - // perror("send width"); + //perror("send width"); return -1; } - - if (send(*kSockHandle, &netHeight, sizeof(netHeight), 0) == -1) + + if(send(*kSockHandle, &netHeight, sizeof(netHeight), 0) == -1) { - // perror("send height"); + //perror("send height"); return -1; } - if (send(*kSockHandle, &netPixelFormat, sizeof(netPixelFormat), 0) == -1) + if(send(*kSockHandle, &netPixelFormat, sizeof(netPixelFormat), 0) == -1) { - // perror("send pixel format"); + //perror("send pixel format"); return -1; } return 0; } -// close TCP connection + + +//close TCP connection int camCloseTcpConnection(int *kSockHandle) { - if (*kSockHandle != -1) + if(*kSockHandle!=-1) { - if (close(*kSockHandle) == -1) + if(close(*kSockHandle)==-1) { perror("close"); - return -1; + return -1; } - *kSockHandle = -1; + *kSockHandle=-1; } return 0; } -// send 8bit frame over the opened TCP connection -int camSendFrameOnTcp(int *kSockHandle, int width, int height, - void *frame8bit) + + +//send 8bit frame over the opened TCP connection +int camSendFrameOnTcp(int *kSockHandle, int width, int height, void *frame8bit) { #ifdef debug - cout << "camSendFrameOnTcp. Handle:" << *kSockHandle << endl; + cout << "camSendFrameOnTcp. Handle:" << *kSockHandle << endl; #endif - if (*kSockHandle != -1) + if(*kSockHandle!=-1) { - int total = 0; // how many bytes we've sent - int bytesleft = width * height; // how many we have left to send + int total = 0; // how many bytes we've sent + int bytesleft = width*height; // how many we have left to send int n; - while (total < width * height) // Send frame + while(total < width*height) // Send frame { - n = send(*kSockHandle, (void *)((char *)frame8bit + total), bytesleft, - 0); // flags: 0, MSG_DONTWAIT - if (n == -1) - { - printf("TCP send failed. Code: %d | %s\n", errno, strerror(errno)); - if (errno == 11) // Resource temporarily unavailable + n=send(*kSockHandle, (void *)((char *)frame8bit+total), bytesleft, 0); //flags: 0, MSG_DONTWAIT + if (n == -1) { - return -1; - } // return without close the connection - camCloseTcpConnection(kSockHandle); // if send fail -> close socket - return -1; - } - else - { - total += n; - bytesleft -= n; - // printf("Sent %d bytes. Bytesleft %d.\n", n, bytesleft); //%zu - if (bytesleft != 0) + printf("TCP send failed. Code: %d | %s\n",errno,strerror(errno)); + if(errno==11) //Resource temporarily unavailable + { + return -1; + } //return without close the connection + camCloseTcpConnection(kSockHandle); //if send fail -> close socket + return -1; + } + else { - printf("Wait for sending remaining bytes...\n"); - // usleep(100000);//100ms + total += n; + bytesleft -= n; +// printf("Sent %d bytes. Bytesleft %d.\n", n, bytesleft); //%zu + if(bytesleft!=0) + { + printf("Wait for sending remaining bytes...\n"); + // usleep(100000);//100ms + } } - } } #ifdef debug - cout << "Frame spedito su TCP.\n" - << endl; + cout << "Frame spedito su TCP.\n" << endl; #endif - } + } else { - return -1; - } + return -1; + } return 0; } -int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, - unsigned char *frame8bit, bool adjLimits, - unsigned int *lowLim, unsigned int *highLim, - unsigned int minLim, unsigned int maxLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH) -{ - // when adjLimits==0, lowLim and highLim are used to adjust the frame. minLim - // and maxLim are NOT used. minLim & maxLim depend on specific camera and are - // used only if adjLimits==1. In this case lowLim and highLim are calculated in - // the frame but cannot exceed the minLim and maxLim. frame8bit is the 8 bit - // resized version of frame using the passed or calculated min and max limits - int pixelSize = getPixelSize(pixelFormat); - - unsigned int minpix, maxpix; - - if (adjLimits) - { - maxpix = 0; - - if (pixelSize <= 8) - minpix = UCHAR_MAX; - else if (pixelSize <= 16) - minpix = USHRT_MAX; - else if (pixelSize <= 32) - minpix = UINT_MAX; - - for (int row = adjRoiY; row < adjRoiY + adjRoiH; - row++) // calculate min & max pixel only in ROI - { - for (int col = adjRoiX; col < adjRoiX + adjRoiW; col++) - { - int i = (row * width) + col; - if (pixelSize <= 8) - { - char *framePtr = (char *)frame; - if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) - { - minpix = framePtr[i]; - } - if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) - { - maxpix = framePtr[i]; - } - } - else if (pixelSize <= 16) - { - short *framePtr = (short *)frame; - if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) - { - minpix = framePtr[i]; - } - if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) - { - maxpix = framePtr[i]; - } - } - else if (pixelSize <= 32) - { - int *framePtr = (int *)frame; - if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) - { - minpix = framePtr[i]; - } - if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) - { - maxpix = framePtr[i]; - } - } - } // for columns - } // for rows - *lowLim = minpix; - *highLim = maxpix; - } - else - { - minpix = *lowLim; - maxpix = *highLim; - } - - unsigned char nsample = 0; // Normalized sample value (between 0 and 255) - float span = (float)(maxpix - minpix + 1); - - // for(int i=0; i maxpix) - { - nsample = 255; - } - else - { - nsample = (unsigned char)(((sample - minpix) / span) * 0xFF); - } - frame8bit[i] = nsample; - } - else if (pixelSize <= 16) - { - short *framePtr = (short *)frame; - unsigned short sample = framePtr[i]; - if (sample < minpix) - { - nsample = 0; - } - else if (sample > maxpix) - { - nsample = 255; - } - else - { - nsample = (unsigned char)(((sample - minpix) / span) * 0xFF); - } - frame8bit[i] = nsample; - } - else if (pixelSize <= 32) - { - int *framePtr = (int *)frame; - unsigned int sample = framePtr[i]; - if (sample < minpix) - { - nsample = 0; - } - else if (sample > maxpix) - { - nsample = 255; - } - else - { - nsample = (unsigned char)(((sample - minpix) / span) * 0xFF); - } - frame8bit[i] = nsample; - } - /* - if(adjLimits && (row==adjRoiY || row==adjRoiY+adjRoiH)) - //mark the region of auto adjust (ROI) +int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, unsigned char *frame8bit, bool adjLimits, unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH) +{ + //when adjLimits==0, lowLim and highLim are used to adjust the frame. minLim and maxLim are NOT used. + //minLim & maxLim depend on specific camera and are used only if adjLimits==1. In this case lowLim and highLim are calculated in the frame but cannot exceed the minLim and maxLim. + //frame8bit is the 8 bit resized version of frame using the passed or calculated min and max limits + + int pixelSize = getPixelSize(pixelFormat); + + unsigned int minpix, maxpix; + + if (adjLimits) + { + maxpix = 0; + + if(pixelSize<=8) + minpix = UCHAR_MAX; + else if(pixelSize<=16) + minpix = USHRT_MAX; + else if(pixelSize<=32) + minpix = UINT_MAX; + + for(int row=adjRoiY; row minLim) && (framePtr[i] < minpix)) + { + minpix = framePtr[i]; + } + if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) + { + maxpix = framePtr[i]; + } + } + else if(pixelSize<=16) + { + short *framePtr = (short *)frame; + if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) + { + minpix = framePtr[i]; + } + if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) + { + maxpix = framePtr[i]; + } + } + else if(pixelSize<=32) + { + int *framePtr = (int *)frame; + if ((framePtr[i] > minLim) && (framePtr[i] < minpix)) + { + minpix = framePtr[i]; + } + if ((framePtr[i] < maxLim) && (framePtr[i] > maxpix)) + { + maxpix = framePtr[i]; + } + } + }//for columns + }//for rows + *lowLim = minpix; + *highLim = maxpix; + } + else + { + minpix = *lowLim; + maxpix = *highLim; + } + + unsigned char nsample = 0; // Normalized sample value (between 0 and 255) + float span = (float)(maxpix - minpix + 1); + + //for(int i=0; i maxpix) + { + nsample = 255; + } + else + { + nsample = (unsigned char) (((sample - minpix) / span) * 0xFF); + } + frame8bit[i] = nsample; } - if(adjLimits && (col==adjRoiX || col==adjRoiX+adjRoiW)) + else if(pixelSize<=16) { - frame8bit[i] = 0xFF; + short *framePtr = (short *)frame; + unsigned short sample = framePtr[i]; + if (sample < minpix) + { + nsample = 0; + } + else if (sample > maxpix) + { + nsample = 255; + } + else + { + nsample = (unsigned char) (((sample - minpix) / span) * 0xFF); + } + frame8bit[i] = nsample; } - */ - } // for col - } // for row + else if(pixelSize<=32) + { + int *framePtr = (int *)frame; + unsigned int sample = framePtr[i]; + if (sample < minpix) + { + nsample = 0; + } + else if (sample > maxpix) + { + nsample = 255; + } + else + { + nsample = (unsigned char) (((sample - minpix) / span) * 0xFF); + } + frame8bit[i] = nsample; + } +/* + if(adjLimits && (row==adjRoiY || row==adjRoiY+adjRoiH)) //mark the region of auto adjust (ROI) + { + frame8bit[i] = 0xFF; + } + if(adjLimits && (col==adjRoiX || col==adjRoiX+adjRoiW)) + { + frame8bit[i] = 0xFF; + } +*/ + }//for col + }//for row } -// IMPORTANT: the file used by drawtext filter in ffmpeg is reload every frame -// processed and so any operation on it MUST BE an atomic operation!!! + +//IMPORTANT: the file used by drawtext filter in ffmpeg is reload every frame processed and so any operation on it MUST BE an atomic operation!!! int camFFMPEGoverlay(const char *filename, const char *textString) { char pathname[100]; - strcpy(pathname, ""); // Clear local filename - strcat(pathname, getenv("HOME")); // get home dir + strcpy(pathname,""); // Clear local filename + strcat(pathname,getenv("HOME")); // get home dir strcat(pathname, "/"); - strcat(pathname, filename); // append my filename + strcat(pathname, filename); // append my filename - char tmp_pathname[strlen(pathname) + - 2]; // temp file to modify let the operation be atomic - snprintf(tmp_pathname, sizeof(tmp_pathname), "%s~", pathname); + char tmp_pathname[strlen(pathname)+2]; //temp file to modify let the operation be atomic + snprintf(tmp_pathname,sizeof(tmp_pathname),"%s~",pathname); - mode_t default_mode = - S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; - int fd = open(tmp_pathname, O_RDWR | O_CREAT | O_TRUNC, default_mode); - if (fd == -1) + mode_t default_mode=S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH; + int fd=open(tmp_pathname,O_RDWR|O_CREAT|O_TRUNC,default_mode); + if (fd==-1) { printf("Failed to open new file for writing\n"); return -1; @@ -691,26 +656,27 @@ int camFFMPEGoverlay(const char *filename, const char *textString) size_t count = write(fd, textString, strlen(textString)); - if (count != strlen(textString)) + if(count!=strlen(textString)) { - printf("Failed to write new content on file\n"); - return -1; + printf("Failed to write new content on file\n"); + return -1; } - if (fsync(fd) == -1) + if (fsync(fd)==-1) { - printf("Failed to flush new file content to disc\n"); - return -1; + printf("Failed to flush new file content to disc\n"); + return -1; } - if (close(fd) == -1) + if (close(fd)==-1) { printf("Failed to close new file\n"); return -1; } - if (rename(tmp_pathname, pathname) == -1) + if (rename(tmp_pathname,pathname)==-1) { printf("Failed to move new file to final location\n"); return -1; } - return 0; + return 0; } + diff --git a/device_support/camera_utils/camstreamutils.h b/device_support/camera_utils/camstreamutils.h index e582cf0519..b8104689cc 100644 --- a/device_support/camera_utils/camstreamutils.h +++ b/device_support/camera_utils/camstreamutils.h @@ -1,42 +1,30 @@ #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif -// SUPPORTED PIXEL FORMATS derived from 'ffmpeg/libavutil/pixfmt.h' -// DEFINES MUST BE ALSO IN ffmpeg/libavdevices/tcpframes.c + +//SUPPORTED PIXEL FORMATS derived from 'ffmpeg/libavutil/pixfmt.h' +//DEFINES MUST BE ALSO IN ffmpeg/libavdevices/tcpframes.c #define CSU_PIX_FMT_NONE 0 -#define CSU_PIX_FMT_GRAY8 1 ///< Y , 8bpp -#define CSU_PIX_FMT_GRAY16 \ - 2 ///< Y , 16bpp (should have big-endian and little-endian /< formats) -#define CSU_PIX_FMT_BAYER_RGGB8 \ - 3 ///< bayer, RGRG..(odd line), GBGB..(even line), 8-bit samples */ -#define CSU_PIX_FMT_YUV422_Packed \ - 4 ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) - - int camOpenTcpConnection(const char *streamingServer, int StreamingPort, - int *kSockHandle, int width, int height, - int pixelFormat); - int camCloseTcpConnection(int *kSockHandle); - int camSendFrameOnTcp(int *kSockHandle, int width, int height, void *frame8bit); - int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, - unsigned char *frame8bit, bool adjLimits, - unsigned int *lowLim, unsigned int *highLim, - unsigned int minLim, unsigned int maxLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH); - int camFFMPEGoverlay(const char *filename, const char *textString); - - void camStreamingFrame(int tcpStreamHandle, void *frame, int width, int height, - int pixelFormat, int irFrameFormat, bool adjLimit, - unsigned int *lowLim, unsigned int *highLim, - unsigned int minLim, unsigned int maxLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName, void *streamingListPtr); - - static void *handleStreaming(void *listPtr); - void camStartStreaming(void **retList); - void camStopStreaming(void *listPtr); +#define CSU_PIX_FMT_GRAY8 1 ///< Y , 8bpp +#define CSU_PIX_FMT_GRAY16 2 ///< Y , 16bpp (should have big-endian and little-endian formats) +#define CSU_PIX_FMT_BAYER_RGGB8 3 ///< bayer, RGRG..(odd line), GBGB..(even line), 8-bit samples */ +#define CSU_PIX_FMT_YUV422_Packed 4 ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) + + +int camOpenTcpConnection(const char *streamingServer, int StreamingPort, int *kSockHandle, int width, int height, int pixelFormat); +int camCloseTcpConnection(int *kSockHandle); +int camSendFrameOnTcp(int *kSockHandle, int width, int height, void *frame8bit); +int camFrameTo8bit(void *frame, int width, int height, int pixelFormat, unsigned char *frame8bit, bool adjLimits, unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH); +int camFFMPEGoverlay(const char *filename, const char *textString); + +void camStreamingFrame(int tcpStreamHandle, void *frame, int width, int height, int pixelFormat, int irFrameFormat, bool adjLimit, unsigned int *lowLim, unsigned int *highLim, unsigned int minLim, unsigned int maxLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName, void *streamingListPtr); + +static void *handleStreaming(void *listPtr); +void camStartStreaming(void **retList); +void camStopStreaming(void *listPtr); #ifdef __cplusplus } #endif + diff --git a/device_support/flir/FLIRSC65X.cpp b/device_support/flir/FLIRSC65X.cpp index c590f4acfc..b4eb4c3669 100644 --- a/device_support/flir/FLIRSC65X.cpp +++ b/device_support/flir/FLIRSC65X.cpp @@ -40,2147 +40,1731 @@ using namespace std; #include #include -#define BUFFER_COUNT 16 +#define BUFFER_COUNT 16 #define ERROR -1 #define SUCCESS 0 -// if defined, print to stdout messages. +//if defined, print to stdout messages. #define debug + #define MAX_CAM 10 static FLIR_SC65X *camPtr[MAX_CAM] = {0}; static char errorOnOpen[512]; -#ifdef __cplusplus -extern "C" + +#ifdef __cplusplus +extern "C" +{ +#endif + + +int flirOpen(const char *ipAddress, int *camHandle) { -#endif + FLIR_SC65X *cam; + int cameraHandle; + + errorOnOpen[0] = 0; + + cam = new FLIR_SC65X(ipAddress); + if(!cam->checkLastOp()) + { + cam->getLastError(errorOnOpen); + delete(cam); + return ERROR; + } + + for( cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle] ; cameraHandle++); + + if( cameraHandle < MAX_CAM ) + { + camPtr[cameraHandle] = cam; + *camHandle = cameraHandle; + return SUCCESS; + } + else + { + sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); + *camHandle = -1; + return ERROR; + } +} - int flirOpen(const char *ipAddress, int *camHandle) - { - FLIR_SC65X *cam; - int cameraHandle; - errorOnOpen[0] = 0; +int flirIsConnected( int camHandle ) +{ + if( camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0 ) + { + sprintf(errorOnOpen, "Camera does not connect"); + return ERROR; + } + return SUCCESS; +} - cam = new FLIR_SC65X(ipAddress); - if (!cam->checkLastOp()) - { - cam->getLastError(errorOnOpen); - delete (cam); - return ERROR; - } +int flirClose(int camHandle) +{ + delete(camPtr[camHandle]); + camPtr[camHandle] = 0; + + return SUCCESS; +} - for (cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle]; - cameraHandle++) - ; - if (cameraHandle < MAX_CAM) - { - camPtr[cameraHandle] = cam; - *camHandle = cameraHandle; - return SUCCESS; - } - else - { - sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); - *camHandle = -1; - return ERROR; - } - } +int checkLastOp(int camHandle) +{ + return camPtr[camHandle]->checkLastOp(); +} - int flirIsConnected(int camHandle) - { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) - { - sprintf(errorOnOpen, "Camera does not connect"); - return ERROR; - } - return SUCCESS; - } - int flirClose(int camHandle) - { - delete (camPtr[camHandle]); - camPtr[camHandle] = 0; +int printAllParameters(int camHandle) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->printAllParameters(); + return ERROR; +} - return SUCCESS; - } - - int checkLastOp(int camHandle) { return camPtr[camHandle]->checkLastOp(); } - - int printAllParameters(int camHandle) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->printAllParameters(); - return ERROR; - } - - int setExposureMode(int camHandle, EXPMODE_ENUM exposureMode) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setExposureMode(exposureMode); - return ERROR; - } - - int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setFrameRate(frameRate, frameToSkip); - return ERROR; - } - - int setFrameRateNew(int camHandle, double frameRate) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setFrameRate(frameRate); - return ERROR; - } - - int setIrFormat(int camHandle, IRFMT_ENUM irFormat) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setIrFormat(irFormat); - return ERROR; - } - - int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->getReadoutArea(x, y, width, height); - return ERROR; - } - - int setReadoutArea(int camHandle, int x, int y, int width, int height) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setReadoutArea(x, y, width, height); - return ERROR; - } - - int setObjectParameters(int camHandle, double reflectedTemperature, - double atmosphericTemperature, double objectDistance, - double objectEmissivity, double relativeHumidity, - double extOpticsTemperature, - double extOpticsTransmission, - double estimatedTransmission) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setObjectParameters( - reflectedTemperature, atmosphericTemperature, objectDistance, - objectEmissivity, relativeHumidity, extOpticsTemperature, - extOpticsTransmission, estimatedTransmission); - return ERROR; - } - - int setMeasurementRange(int camHandle, int measRange) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setMeasurementRange(measRange); - return ERROR; - } - - int getFocusAbsPosition(int camHandle, int *focusPos) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->getFocusAbsPosition(focusPos); - return ERROR; - } - - int setFocusAbsPosition(int camHandle, int focusPos) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setFocusAbsPosition(focusPos); - return ERROR; - } - - int executeAutoFocus(int camHandle) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->executeAutoFocus(); - return ERROR; - } - - int setCalibMode(int camHandle, int calMode) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setCalibMode(calMode); - return ERROR; - } - - int executeAutoCalib(int camHandle) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->executeAutoCalib(); - return ERROR; - } - - int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startAcquisition(width, height, payloadSize); - return ERROR; - } - - int stopAcquisition(int camHandle) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopAcquisition(); - return ERROR; - } - - int getFrame(int camHandle, int *status, void *frame, void *metaData) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->getFrame(status, frame, metaData); - return ERROR; - } - - int frameConv(int camHandle, unsigned short *frame, int width, int height) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->frameConv(frame, width, height); - return ERROR; - } - - int setAcquisitionMode(int camHandle, int storeEnabled, - int acqSkipFrameNumber) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setAcquisitionMode(storeEnabled, - acqSkipFrameNumber); - return ERROR; - } - - int setTriggerMode(int camHandle, int triggerMode, double burstDuration, - int numTrigger) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTriggerMode(triggerMode, burstDuration, - numTrigger); - return ERROR; - } - - int softwareTrigger(int camHandle) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->softwareTrigger(); - return ERROR; - } - - int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTreeInfo(treePtr, framesNid, timebaseNid, - framesMetadNid, frame0TimeNid); - return ERROR; - } - - int setStreamingMode(int camHandle, IRFMT_ENUM irFormat, int streamingEnabled, - bool autoAdjustLimit, const char *streamingServer, - int streamingPort, int lowLim, int highLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setStreamingMode( - irFormat, streamingEnabled, autoAdjustLimit, streamingServer, - streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, - deviceName); - return ERROR; - } - int startFramesAcquisition(int camHandle) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startFramesAcquisition(); - return ERROR; - } - - int stopFramesAcquisition(int camHandle) - { - if (flirIsConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopFramesAcquisition(); - return ERROR; - } - - void getLastError(int camHandle, char *msg) - { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) - { - sprintf(msg, "%s", (errorOnOpen[0] == 0) ? "" : errorOnOpen); - return; - } - camPtr[camHandle]->getLastError(msg); - } -#ifdef __cplusplus +int setExposureMode(int camHandle, EXPMODE_ENUM exposureMode) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setExposureMode(exposureMode); + return ERROR; } -#endif -FLIR_SC65X::FLIR_SC65X(const char *ipAddress) + +int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip) { - this->ipAddress = PvString(ipAddress); - - /* SDK 3 - this->lDevice = new PvDevice(); - this->lResult = this->lDevice->Connect(this->ipAddress, - PvAccessExclusive); - */ - try - { - this->lDevice = PvDevice::CreateAndConnect( - this->ipAddress, - &this->lResult); // 20160309 SDK4 //sometimes goes in coredump - } - catch (...) - { - printf("Core dump detected on PvDevice::CreateAndConnect\n"); - } - if (!this->lResult.IsOK()) - { - printf( - "--------------------------------- Error Device connection: (%s) %p\n", - this->lResult.GetCodeString().GetAscii(), this->lDevice); - if (this->lDevice != nullptr) // CT 2019-03-29 - { - PvDevice::Free(this->lDevice); - } - } - else - { - printf("---------------------------- OK Device connection: (%s)\n", - this->lResult.GetDescription().GetAscii()); - } + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setFrameRate(frameRate, frameToSkip); + return ERROR; } -FLIR_SC65X::FLIR_SC65X() // new 25/07/2013: let to use the device without the - // camera + +int setFrameRateNew(int camHandle, double frameRate) { - // this->lDevice = new PvDevice(); //SDK 3 - // SDK 4 09/03/2016 NON sembra possibile creare un PVDEVICE se non ho la - // telecamera + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setFrameRate(frameRate); + return ERROR; } -FLIR_SC65X::~FLIR_SC65X() + +int setIrFormat(int camHandle, IRFMT_ENUM irFormat) { - printf("FLIR_SC65X destructor %p\n", this->lDevice); - if (this->lDevice != nullptr) // CT 2019-03-27 - { - this->lResult = this->lDevice->Disconnect(); - if (!this->lResult.IsOK()) - printLastError("Error Device disconnection !!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - else - printf("FLIR_SC65X destructor class executed\n"); - // delete(this->lDevice); //SDK 3 - PvDevice::Free(this->lDevice); // SDK 4 09/03/2016 - } + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setIrFormat(irFormat); + return ERROR; } -int FLIR_SC65X::checkLastOp() + +int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height) { - printf("Info %d (%s)\n", this->lResult.IsOK(), - lResult.GetDescription().GetAscii()); - if (!this->lResult.IsOK()) - printLastError("(%s)\n", lResult.GetDescription().GetAscii()); - return this->lResult.IsOK(); + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->getReadoutArea(x, y, width, height); + return ERROR; } -int FLIR_SC65X::printAllParameters() + +int setReadoutArea(int camHandle, int x, int y, int width, int height) { - PvGenParameterArray *aArray = lDevice->GetParameters(); - uint32_t lParameterArrayCount = aArray->GetCount(); - printf("\nArray has %d parameters\n", lParameterArrayCount); - - // Traverse through Array and print out parameters available - for (uint32_t x = 0; x < lParameterArrayCount; x++) - { - // Get a parameter - PvGenParameter *lGenParameter = aArray->Get(x); - - // Don't show invisible parameters - display everything up to Guru - if (!lGenParameter->IsVisible(PvGenVisibilityGuru)) - { - continue; - } + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setReadoutArea(x, y, width, height); + return ERROR; +} - // Get and print parameter's name - PvString lGenParameterName, lCategory; - lGenParameter->GetCategory(lCategory); - lGenParameter->GetName(lGenParameterName); - printf("%s:%s, ", lCategory.GetAscii(), lGenParameterName.GetAscii()); - // Parameter available? - if (!lGenParameter->IsAvailable()) - { - printf("{Not Available}\n"); - continue; - } +int setObjectParameters(int camHandle, double reflectedTemperature, double atmosphericTemperature, + double objectDistance, double objectEmissivity, + double relativeHumidity, double extOpticsTemperature, + double extOpticsTransmission, double estimatedTransmission) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setObjectParameters(reflectedTemperature, atmosphericTemperature, objectDistance, objectEmissivity, relativeHumidity, extOpticsTemperature, extOpticsTransmission, estimatedTransmission); + return ERROR; +} - // Parameter readable? - if (!lGenParameter->IsReadable()) - { - printf("{Not readable}\n"); - continue; - } - // Get the parameter type - PvGenType lType; - lGenParameter->GetType(lType); - switch (lType) - { - // If the parameter is of type PvGenTypeInteger - case PvGenTypeInteger: - { - int64_t lValue; - static_cast(lGenParameter)->GetValue(lValue); - printf("Integer: %d", lValue); - } - break; - // If the parameter is of type PvGenTypeEnum - case PvGenTypeEnum: - { - PvString lValue; - static_cast(lGenParameter)->GetValue(lValue); - printf("Enum: %s", lValue.GetAscii()); - } - break; - // If the parameter is of type PvGenTypeBoolean - case PvGenTypeBoolean: - { - bool lValue; - static_cast(lGenParameter)->GetValue(lValue); - if (lValue) - { - printf("Boolean: TRUE"); - } - else - { - printf("Boolean: FALSE"); - } +int setMeasurementRange(int camHandle, int measRange) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setMeasurementRange(measRange); + return ERROR; +} + + +int getFocusAbsPosition(int camHandle, int *focusPos) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->getFocusAbsPosition(focusPos); + return ERROR; +} + + +int setFocusAbsPosition(int camHandle, int focusPos) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setFocusAbsPosition(focusPos); + return ERROR; +} + + +int executeAutoFocus(int camHandle) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->executeAutoFocus(); + return ERROR; +} + + +int setCalibMode(int camHandle, int calMode) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setCalibMode(calMode); + return ERROR; +} + + +int executeAutoCalib(int camHandle) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->executeAutoCalib(); + return ERROR; +} + + +int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->startAcquisition(width, height, payloadSize); + return ERROR; +} + + +int stopAcquisition(int camHandle) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->stopAcquisition(); + return ERROR; +} + + +int getFrame(int camHandle, int *status, void *frame, void *metaData) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->getFrame(status, frame, metaData); + return ERROR; +} + + +int frameConv(int camHandle, unsigned short *frame, int width, int height) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->frameConv(frame, width, height); + return ERROR; +} + +int setAcquisitionMode( int camHandle, int storeEnabled, int acqSkipFrameNumber) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setAcquisitionMode( storeEnabled, acqSkipFrameNumber); + return ERROR; +} + +int setTriggerMode( int camHandle, int triggerMode, double burstDuration, int numTrigger ) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setTriggerMode( triggerMode, burstDuration, numTrigger ); + return ERROR; +} + +int softwareTrigger(int camHandle) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->softwareTrigger(); + return ERROR; +} + +int setTreeInfo( int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setTreeInfo( treePtr, framesNid, timebaseNid, framesMetadNid, frame0TimeNid ); + return ERROR; +} + +int setStreamingMode(int camHandle, IRFMT_ENUM irFormat, int streamingEnabled, bool autoAdjustLimit, + const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setStreamingMode( irFormat, streamingEnabled, autoAdjustLimit, streamingServer, streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); + return ERROR; + +} +int startFramesAcquisition(int camHandle) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->startFramesAcquisition(); + return ERROR; +} + +int stopFramesAcquisition(int camHandle) +{ + if( flirIsConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->stopFramesAcquisition(); + return ERROR; +} + +void getLastError(int camHandle, char *msg) +{ + if( camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0 ) + { + sprintf(msg, "%s", (errorOnOpen[0]==0) ? "" : errorOnOpen); + return; + } + camPtr[camHandle]->getLastError(msg); +} + + +#ifdef __cplusplus +} +#endif + + + + +FLIR_SC65X::FLIR_SC65X(const char *ipAddress) +{ + this->ipAddress = PvString(ipAddress); + +/* SDK 3 + this->lDevice = new PvDevice(); + this->lResult = this->lDevice->Connect(this->ipAddress, PvAccessExclusive); +*/ + try{ + this->lDevice = PvDevice::CreateAndConnect(this->ipAddress, &this->lResult); //20160309 SDK4 //sometimes goes in coredump } - break; - // If the parameter is of type PvGenTypeString - case PvGenTypeString: + catch(...) { - PvString lValue; - static_cast(lGenParameter)->GetValue(lValue); - printf("String: %s", lValue.GetAscii()); + printf("Core dump detected on PvDevice::CreateAndConnect\n"); } - break; - // If the parameter is of type PvGenTypeCommand - case PvGenTypeCommand: - printf("Command"); - break; - // If the parameter is of type PvGenTypeFloat - case PvGenTypeFloat: + if ( !this->lResult.IsOK() ) { - double lValue; - static_cast(lGenParameter)->GetValue(lValue); - printf("Float: %f", lValue); + printf("--------------------------------- Error Device connection: (%s) %p\n", this->lResult.GetCodeString().GetAscii(), this->lDevice); + if( this->lDevice != nullptr ) //CT 2019-03-29 + { + PvDevice::Free(this->lDevice); + } } - break; + else + { + printf("---------------------------- OK Device connection: (%s)\n", this->lResult.GetDescription().GetAscii() ); } - printf("\n"); - } - return SUCCESS; + + printf("EVENTO abilitato \n"); + //CT MDSplus acquisition Triggered on MDSevent + eventTrigger = 0; + trigEvent = new TriggerMdsEvent("__CCD_TRIGGER__", this); + trigEvent->start(); + } -int FLIR_SC65X::setExposureMode(EXPMODE_ENUM exposureMode) + +FLIR_SC65X::FLIR_SC65X() //new 25/07/2013: let to use the device without the camera { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *currPort = - dynamic_cast(lDeviceParams->Get("CurrentPort")); - PvGenEnum *currCfg = - dynamic_cast(lDeviceParams->Get("CurrentIOConfig")); - - this->lResult = currPort->SetValue(0); - if (!this->lResult.IsOK()) - { - printLastError("Error setting current port to 0!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - switch (exposureMode) - { - case internal_mode: - usleep(3000); - this->lResult = currCfg->SetValue("GeneralPurpose"); - if (!this->lResult.IsOK()) - { - printLastError("Error setting exposure mode!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - else - { - printf("Sync. INTERNAL configured.\n"); - } - break; - case external_mode: - usleep(3000); - this->lResult = currCfg->SetValue("MarkImage"); - if (!this->lResult.IsOK()) + //this->lDevice = new PvDevice(); //SDK 3 + //SDK 4 09/03/2016 NON sembra possibile creare un PVDEVICE se non ho la telecamera +} + + +FLIR_SC65X::~FLIR_SC65X() +{ + printf("FLIR_SC65X destructor %p\n", this->lDevice ); + if( this->lDevice != nullptr ) //CT 2019-03-27 { - printLastError("Error setting exposure mode!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; + this->lResult = this->lDevice->Disconnect(); + if ( !this->lResult.IsOK() ) + printLastError("Error Device disconnection !!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + else + printf("FLIR_SC65X destructor class executed\n"); + //delete(this->lDevice); //SDK 3 + PvDevice::Free(this->lDevice); //SDK 4 09/03/2016 } - else + + if( trigEvent != nullptr ) { - printf("Sync. EXTERNAL configured.\n"); + delete trigEvent; } - break; - } +} - return SUCCESS; + + +int FLIR_SC65X::checkLastOp() +{ + printf("Info %d (%s)\n", this->lResult.IsOK(), lResult.GetDescription().GetAscii() ); + if ( !this->lResult.IsOK() ) + printLastError("(%s)\n", lResult.GetDescription().GetAscii() ); + return this->lResult.IsOK(); +} + + + +int FLIR_SC65X::printAllParameters() +{ + PvGenParameterArray *aArray = lDevice->GetParameters(); + uint32_t lParameterArrayCount = aArray->GetCount(); + printf( "\nArray has %d parameters\n", lParameterArrayCount ); + + // Traverse through Array and print out parameters available + for( uint32_t x = 0; x < lParameterArrayCount; x++ ) + { + // Get a parameter + PvGenParameter *lGenParameter = aArray->Get( x ); + + // Don't show invisible parameters - display everything up to Guru + if ( !lGenParameter->IsVisible( PvGenVisibilityGuru ) ) + { + continue; + } + + // Get and print parameter's name + PvString lGenParameterName, lCategory; + lGenParameter->GetCategory( lCategory ); + lGenParameter->GetName( lGenParameterName ); + printf( "%s:%s, ", lCategory.GetAscii(), lGenParameterName.GetAscii() ); + + // Parameter available? + if ( !lGenParameter->IsAvailable() ) + { + printf( "{Not Available}\n" ); + continue; + } + + // Parameter readable? + if ( !lGenParameter->IsReadable() ) + { + printf( "{Not readable}\n" ); + continue; + } + + // Get the parameter type + PvGenType lType; + lGenParameter->GetType( lType ); + switch ( lType ) + { + // If the parameter is of type PvGenTypeInteger + case PvGenTypeInteger: + { + int64_t lValue; + static_cast( lGenParameter )->GetValue( lValue ); + printf( "Integer: %d", lValue ); + } + break; + // If the parameter is of type PvGenTypeEnum + case PvGenTypeEnum: + { + PvString lValue; + static_cast( lGenParameter )->GetValue( lValue ); + printf( "Enum: %s", lValue.GetAscii() ); + } + break; + // If the parameter is of type PvGenTypeBoolean + case PvGenTypeBoolean: + { + bool lValue; + static_cast( lGenParameter )->GetValue( lValue ); + if( lValue ) + { + printf( "Boolean: TRUE" ); + } + else + { + printf( "Boolean: FALSE" ); + } + } + break; + // If the parameter is of type PvGenTypeString + case PvGenTypeString: + { + PvString lValue; + static_cast( lGenParameter )->GetValue( lValue ); + printf( "String: %s", lValue.GetAscii() ); + } + break; + // If the parameter is of type PvGenTypeCommand + case PvGenTypeCommand: + printf( "Command" ); + break; + // If the parameter is of type PvGenTypeFloat + case PvGenTypeFloat: + { + double lValue; + static_cast( lGenParameter )->GetValue( lValue ); + printf( "Float: %f", lValue ); + } + break; + } + printf("\n"); + } + + return SUCCESS; +} + + + +int FLIR_SC65X::setExposureMode(EXPMODE_ENUM exposureMode) +{ + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *currPort = dynamic_cast( lDeviceParams->Get( "CurrentPort" ) ); + PvGenEnum *currCfg = dynamic_cast( lDeviceParams->Get( "CurrentIOConfig" ) ); + + this->lResult = currPort->SetValue( 0 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting current port to 0!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + switch(exposureMode) + { + case internal_mode: +usleep(3000); + this->lResult = currCfg->SetValue( "GeneralPurpose" ); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting exposure mode!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + else + {printf("Sync. INTERNAL configured.\n");} + break; + case external_mode: +usleep(3000); + this->lResult = currCfg->SetValue( "MarkImage" ); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting exposure mode!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + else + {printf("Sync. EXTERNAL configured.\n");} + break; + } + + return SUCCESS; } int FLIR_SC65X::setFrameRate(double frameRate) { - FPS_ENUM fps; - - if (frameRate == 200.) - fps = fps_200; - else if (fabs(frameRate - 100.) < 1.e-4) - fps = fps_100; - else if (fabs(frameRate - 50.) < 1.e-4) - fps = fps_50; - else if (fabs(frameRate - 25.) < 1.e-4) - fps = fps_25; - else if (fabs(frameRate - 12.5) < 1.e-4) - fps = fps_12; - else if (fabs(frameRate - 6.25) < 1.e-4) - fps = fps_6; - else if (fabs(frameRate - 3.12) < 1.e-4) - fps = fps_3; - - this->frameRate = frameRate; - - return (setFrameRate(fps, &streamingSkipFrameNumber)); + FPS_ENUM fps; + + if ( frameRate == 200.) + fps = fps_200; + else if ( fabs( frameRate - 100. ) < 1.e-4 ) + fps = fps_100; + else if ( fabs( frameRate - 50. ) < 1.e-4 ) + fps = fps_50; + else if ( fabs( frameRate - 25. ) < 1.e-4 ) + fps = fps_25; + else if ( fabs( frameRate - 12.5) < 1.e-4 ) + fps = fps_12; + else if ( fabs( frameRate - 6.25) < 1.e-4 ) + fps = fps_6; + else if ( fabs( frameRate - 3.12) < 1.e-4 ) + fps = fps_3; + + this->frameRate = frameRate; + + return ( setFrameRate(fps, &streamingSkipFrameNumber) ); + } int FLIR_SC65X::setFrameRate(FPS_ENUM fps, int *frameToSkip) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lWidth = - dynamic_cast(lDeviceParams->Get("Width")); - PvGenInteger *lHeight = - dynamic_cast(lDeviceParams->Get("Height")); - PvGenEnum *sWindowing = - dynamic_cast(lDeviceParams->Get("IRWindowing")); - PvGenEnum *sFrameRate = - dynamic_cast(lDeviceParams->Get("IRFrameRate")); - - switch (fps) - { - case fps_200: - usleep(3000); - this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lHeight->SetValue(123); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = sFrameRate->SetValue(0); - if (!this->lResult.IsOK()) - { - printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = sWindowing->SetValue("Quarter"); //"Quarter" - if (!this->lResult.IsOK()) - { - printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lWidth = dynamic_cast( lDeviceParams->Get( "Width" ) ); + PvGenInteger *lHeight = dynamic_cast( lDeviceParams->Get( "Height" ) ); + PvGenEnum *sWindowing = dynamic_cast( lDeviceParams->Get( "IRWindowing" ) ); + PvGenEnum *sFrameRate = dynamic_cast( lDeviceParams->Get( "IRFrameRate" ) ); + + + switch(fps) + { + case fps_200: +usleep(3000); + this->lResult = lWidth->SetValue( 640 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lHeight->SetValue( 123 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = sFrameRate->SetValue(0); + if ( !this->lResult.IsOK() ) {printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = sWindowing->SetValue("Quarter");//"Quarter" + if ( !this->lResult.IsOK() ) {printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} #ifdef debug - printf("Frame rate set to 200Hz.\n"); + printf("Frame rate set to 200Hz.\n"); #endif - *frameToSkip = 8; - break; - - case fps_100: - usleep(3000); - this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lHeight->SetValue(243); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = sFrameRate->SetValue(0); - if (!this->lResult.IsOK()) - { - printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = sWindowing->SetValue("Half"); //"Half" - if (!this->lResult.IsOK()) - { - printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + *frameToSkip = 8; + break; + + case fps_100: +usleep(3000); + this->lResult = lWidth->SetValue( 640 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lHeight->SetValue( 243 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = sFrameRate->SetValue(0); + if ( !this->lResult.IsOK() ) {printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = sWindowing->SetValue("Half"); //"Half" + if ( !this->lResult.IsOK() ) {printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} #ifdef debug - printf("Frame rate set to 100Hz.\n"); + printf("Frame rate set to 100Hz.\n"); #endif - *frameToSkip = 4; - break; - - case fps_50: - usleep(3000); - this->lResult = sFrameRate->SetValue(0); - if (!this->lResult.IsOK()) - { - printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) - { - printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + *frameToSkip = 4; + break; + + case fps_50: +usleep(3000); + this->lResult = sFrameRate->SetValue(0); + if ( !this->lResult.IsOK() ) {printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = sWindowing->SetValue("Off"); //"Off" + if ( !this->lResult.IsOK() ) {printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lWidth->SetValue( 640 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lHeight->SetValue( 483 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} #ifdef debug - printf("Frame rate set to 50Hz.\n"); + printf("Frame rate set to 50Hz.\n"); #endif - *frameToSkip = 2; - break; - - case fps_25: - usleep(3000); - this->lResult = sFrameRate->SetValue(1); - if (!this->lResult.IsOK()) - { - printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) - { - printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + *frameToSkip = 2; + break; + + case fps_25: +usleep(3000); + this->lResult = sFrameRate->SetValue(1); + if ( !this->lResult.IsOK() ) {printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = sWindowing->SetValue("Off"); //"Off" + if ( !this->lResult.IsOK() ) {printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lWidth->SetValue( 640 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lHeight->SetValue( 483 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} #ifdef debug - printf("Frame rate set to 25Hz.\n"); + printf("Frame rate set to 25Hz.\n"); #endif - *frameToSkip = 1; - break; - - case fps_12: - usleep(3000); - this->lResult = sFrameRate->SetValue(2); - if (!this->lResult.IsOK()) - { - printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) - { - printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + *frameToSkip = 1; + break; + + case fps_12: +usleep(3000); + this->lResult = sFrameRate->SetValue(2); + if ( !this->lResult.IsOK() ) {printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lWidth->SetValue( 640 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lHeight->SetValue( 483 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = sWindowing->SetValue("Off"); //"Off" + if ( !this->lResult.IsOK() ) {printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} #ifdef debug - printf("Frame rate set to 12.5Hz.\n"); + printf("Frame rate set to 12.5Hz.\n"); #endif - *frameToSkip = 1; - break; - - case fps_6: - usleep(3000); - this->lResult = sFrameRate->SetValue(3); - if (!this->lResult.IsOK()) - { - printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) - { - printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + *frameToSkip = 1; + break; + + case fps_6: +usleep(3000); + this->lResult = sFrameRate->SetValue(3); + if ( !this->lResult.IsOK() ) {printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lWidth->SetValue( 640 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lHeight->SetValue( 483 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = sWindowing->SetValue("Off"); //"Off" + if ( !this->lResult.IsOK() ) {printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} #ifdef debug - printf("Frame rate set to 6.25Hz.\n"); + printf("Frame rate set to 6.25Hz.\n"); #endif - *frameToSkip = 1; - break; - - case fps_3: - usleep(3000); - this->lResult = sFrameRate->SetValue(4); - if (!this->lResult.IsOK()) - { - printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lWidth->SetValue(640); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lHeight->SetValue(483); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = sWindowing->SetValue("Off"); //"Off" - if (!this->lResult.IsOK()) - { - printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + *frameToSkip = 1; + break; + + case fps_3: +usleep(3000); + this->lResult = sFrameRate->SetValue(4); + if ( !this->lResult.IsOK() ) {printLastError("Error setting FrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lWidth->SetValue( 640 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lHeight->SetValue( 483 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = sWindowing->SetValue("Off"); //"Off" + if ( !this->lResult.IsOK() ) {printLastError("Error setting Windowing in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} #ifdef debug - printf("Frame rate set to 3.12Hz.\n"); + printf("Frame rate set to 3.12Hz.\n"); #endif - *frameToSkip = 1; - break; - - default: - printLastError("Invalid frame rate value!!!\n", 0); - return ERROR; - } + *frameToSkip = 1; + break; - usleep(3500000); + default: + printLastError("Invalid frame rate value!!!\n", 0); + return ERROR; + } - return SUCCESS; +usleep(3500000); + + return SUCCESS; } + + int FLIR_SC65X::setIrFormat(IRFMT_ENUM irFormat) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenEnum *sFormat = - dynamic_cast(lDeviceParams->Get("IRFormat")); - - switch (irFormat) - { - case radiometric: - this->lResult = sFormat->SetValue("Radiometric"); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Radiometric in setIrFormat!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - else - { - printf("IR FORMAT set to radiometric.\n"); - } - break; - case linear100mK: - this->lResult = sFormat->SetValue("TemperatureLinear100mK"); - if (!this->lResult.IsOK()) - { - printLastError("Error setting TemperatureLinear100mK!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - else - { - printf("IR FORMAT set to TemperatureLinear100mK.\n"); - } - break; - case linear10mK: - this->lResult = sFormat->SetValue("TemperatureLinear10mK"); - if (!this->lResult.IsOK()) - { - printLastError("Error setting TemperatureLinear10mK!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - else - { - printf("IR FORMAT set to TemperatureLinear10mK.\n"); - } - break; - } + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenEnum *sFormat = dynamic_cast( lDeviceParams->Get( "IRFormat" ) ); + + switch(irFormat) + { + case radiometric: + this->lResult = sFormat->SetValue("Radiometric"); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting Radiometric in setIrFormat!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + else + {printf("IR FORMAT set to radiometric.\n");} + break; + case linear100mK: + this->lResult = sFormat->SetValue("TemperatureLinear100mK"); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting TemperatureLinear100mK!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + else + {printf("IR FORMAT set to TemperatureLinear100mK.\n");} + break; + case linear10mK: + this->lResult = sFormat->SetValue("TemperatureLinear10mK"); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting TemperatureLinear10mK!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + else + {printf("IR FORMAT set to TemperatureLinear10mK.\n");} + break; + } + + this->irFrameFormat = irFormat; + + + return SUCCESS; +} - this->irFrameFormat = irFormat; - return SUCCESS; -} int FLIR_SC65X::getReadoutArea(int *x, int *y, int *width, int *height) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lWidth = - dynamic_cast(lDeviceParams->Get("Width")); - PvGenInteger *lHeight = - dynamic_cast(lDeviceParams->Get("Height")); - PvGenInteger *lOffsetX = - dynamic_cast(lDeviceParams->Get("OffsetX")); - PvGenInteger *lOffsetY = - dynamic_cast(lDeviceParams->Get("OffsetY")); - - int64_t ox = 0; - int64_t oy = 0; - int64_t w = 0; - int64_t h = 0; - - this->lResult = lWidth->GetValue(w); - if (!this->lResult.IsOK()) - { - printLastError("Error getting Width in getReadoutArea\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lHeight->GetValue(h); - if (!this->lResult.IsOK()) - { - printLastError("Error getting Height in getReadoutArea\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lOffsetX->GetValue(ox); - if (!this->lResult.IsOK()) - { - printLastError("Error getting OffsetX in getReadoutArea\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lOffsetY->GetValue(oy); - if (!this->lResult.IsOK()) - { - printLastError("Error getting OffsetY in getReadoutArea\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - this->x = *x = (int)ox; - this->y = *y = (int)oy; - this->width = *width = (int)w; - this->height = *height = (int)h - 3; // remove 3 lines of metadata - - return SUCCESS; + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lWidth = dynamic_cast( lDeviceParams->Get( "Width" ) ); + PvGenInteger *lHeight = dynamic_cast( lDeviceParams->Get( "Height" ) ); + PvGenInteger *lOffsetX = dynamic_cast( lDeviceParams->Get( "OffsetX" ) ); + PvGenInteger *lOffsetY = dynamic_cast( lDeviceParams->Get( "OffsetY" ) ); + + int64_t ox = 0; + int64_t oy = 0; + int64_t w = 0; + int64_t h = 0; + + + this->lResult = lWidth->GetValue( w ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting Width in getReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lHeight->GetValue( h ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting Height in getReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lOffsetX->GetValue( ox ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting OffsetX in getReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lOffsetY->GetValue( oy ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting OffsetY in getReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + this->x = *x=(int)ox; + this->y = *y=(int)oy; + this->width = *width=(int)w; + this->height = *height=(int)h-3; //remove 3 lines of metadata + + + return SUCCESS; } + + int FLIR_SC65X::setReadoutArea(int x, int y, int width, int height) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lWidth = - dynamic_cast(lDeviceParams->Get("Width")); - PvGenInteger *lHeight = - dynamic_cast(lDeviceParams->Get("Height")); - PvGenInteger *lOffsetX = - dynamic_cast(lDeviceParams->Get("OffsetX")); - PvGenInteger *lOffsetY = - dynamic_cast(lDeviceParams->Get("OffsetY")); - - int64_t w = width; - int64_t h = height; - int64_t ox = x; - int64_t oy = y; - - this->lResult = lWidth->SetValue(w); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Width in setReadoutArea\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lHeight->SetValue(h + 3); // add 3 lines of metadata - if (!this->lResult.IsOK()) - { - printLastError("Error setting Height in setReadoutArea\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lOffsetX->SetValue(ox); - if (!this->lResult.IsOK()) - { - printLastError("Error setting OffsetX in setReadoutArea\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lOffsetY->SetValue(oy); - if (!this->lResult.IsOK()) - { - printLastError("Error setting OffsetY in setReadoutArea\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - this->x = x; - this->y = y; - this->width = width; - this->height = height; - - return SUCCESS; + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lWidth = dynamic_cast( lDeviceParams->Get( "Width" ) ); + PvGenInteger *lHeight = dynamic_cast( lDeviceParams->Get( "Height" ) ); + PvGenInteger *lOffsetX = dynamic_cast( lDeviceParams->Get( "OffsetX" ) ); + PvGenInteger *lOffsetY = dynamic_cast( lDeviceParams->Get( "OffsetY" ) ); + + int64_t w = width; + int64_t h = height; + int64_t ox = x; + int64_t oy = y; + + + this->lResult = lWidth->SetValue(w); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lHeight->SetValue(h+3); //add 3 lines of metadata + if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lOffsetX->SetValue(ox); + if ( !this->lResult.IsOK() ) {printLastError("Error setting OffsetX in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} +usleep(3000); + this->lResult = lOffsetY->SetValue(oy); + if ( !this->lResult.IsOK() ) {printLastError("Error setting OffsetY in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + this->x = x; + this->y = y; + this->width = width; + this->height = height; + + + return SUCCESS; } -int FLIR_SC65X::setObjectParameters( - double reflectedTemperature, double atmosphericTemperature, - double objectDistance, double objectEmissivity, double relativeHumidity, - double extOpticsTemperature, double extOpticsTransmission, - double estimatedTransmission) + + +int FLIR_SC65X::setObjectParameters(double reflectedTemperature, double atmosphericTemperature, double objectDistance, double objectEmissivity, double relativeHumidity, double extOpticsTemperature, double extOpticsTransmission, double estimatedTransmission) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenFloat *RefTemp = - dynamic_cast(lDeviceParams->Get("ReflectedTemperature")); - PvGenFloat *AtmTemp = - dynamic_cast(lDeviceParams->Get("AtmosphericTemperature")); - PvGenFloat *ObjDist = - dynamic_cast(lDeviceParams->Get("ObjectDistance")); - PvGenFloat *ObjEmis = - dynamic_cast(lDeviceParams->Get("ObjectEmissivity")); - PvGenFloat *RelHumi = - dynamic_cast(lDeviceParams->Get("RelativeHumidity")); - PvGenFloat *EopTemp = - dynamic_cast(lDeviceParams->Get("ExtOpticsTemperature")); - PvGenFloat *EopTran = - dynamic_cast(lDeviceParams->Get("ExtOpticsTransmission")); - PvGenFloat *EstTran = - dynamic_cast(lDeviceParams->Get("EstimatedTransmission")); - - this->lResult = RefTemp->SetValue(reflectedTemperature + 273.15); - if (!this->lResult.IsOK()) - { - printLastError("Error setting reflectedTemperature!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - usleep(3000); - this->lResult = AtmTemp->SetValue(atmosphericTemperature + 273.15); - if (!this->lResult.IsOK()) - { - printLastError("Error setting atmosphericTemperature!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - usleep(3000); - this->lResult = ObjDist->SetValue(objectDistance); - if (!this->lResult.IsOK()) - { - printLastError("Error setting objectDistance!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - usleep(3000); - this->lResult = ObjEmis->SetValue(objectEmissivity); - if (!this->lResult.IsOK()) - { - printLastError("Error setting objectEmissivity!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - usleep(3000); - this->lResult = RelHumi->SetValue(relativeHumidity); - if (!this->lResult.IsOK()) - { - printLastError("Error setting relativeHumidity!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - usleep(3000); - this->lResult = EopTemp->SetValue(extOpticsTemperature + 273.15); - if (!this->lResult.IsOK()) - { - printLastError("Error setting extOpticsTemperature!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - usleep(3000); - this->lResult = EopTran->SetValue(extOpticsTransmission); - if (!this->lResult.IsOK()) - { - printLastError("Error setting extOpticsTransmission!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - usleep(3000); - this->lResult = EstTran->SetValue(estimatedTransmission); - if (!this->lResult.IsOK()) - { - printLastError("Error setting estimatedTransmission!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - return SUCCESS; + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenFloat *RefTemp = dynamic_cast( lDeviceParams->Get( "ReflectedTemperature" ) ); + PvGenFloat *AtmTemp = dynamic_cast( lDeviceParams->Get( "AtmosphericTemperature" ) ); + PvGenFloat *ObjDist = dynamic_cast( lDeviceParams->Get( "ObjectDistance" ) ); + PvGenFloat *ObjEmis = dynamic_cast( lDeviceParams->Get( "ObjectEmissivity" ) ); + PvGenFloat *RelHumi = dynamic_cast( lDeviceParams->Get( "RelativeHumidity" ) ); + PvGenFloat *EopTemp = dynamic_cast( lDeviceParams->Get( "ExtOpticsTemperature" ) ); + PvGenFloat *EopTran = dynamic_cast( lDeviceParams->Get( "ExtOpticsTransmission" ) ); + PvGenFloat *EstTran = dynamic_cast( lDeviceParams->Get( "EstimatedTransmission" ) ); + + + + this->lResult = RefTemp->SetValue(reflectedTemperature + 273.15); + if ( !this->lResult.IsOK() ) {printLastError("Error setting reflectedTemperature!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +usleep(3000); + this->lResult = AtmTemp->SetValue(atmosphericTemperature + 273.15); + if ( !this->lResult.IsOK() ) {printLastError("Error setting atmosphericTemperature!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +usleep(3000); + this->lResult = ObjDist->SetValue(objectDistance); + if ( !this->lResult.IsOK() ) {printLastError("Error setting objectDistance!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +usleep(3000); + this->lResult = ObjEmis->SetValue(objectEmissivity); + if ( !this->lResult.IsOK() ) {printLastError("Error setting objectEmissivity!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +usleep(3000); + this->lResult = RelHumi->SetValue(relativeHumidity); + if ( !this->lResult.IsOK() ) {printLastError("Error setting relativeHumidity!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +usleep(3000); + this->lResult = EopTemp->SetValue(extOpticsTemperature + 273.15); + if ( !this->lResult.IsOK() ) {printLastError("Error setting extOpticsTemperature!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +usleep(3000); + this->lResult = EopTran->SetValue(extOpticsTransmission); + if ( !this->lResult.IsOK() ) {printLastError("Error setting extOpticsTransmission!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +usleep(3000); + this->lResult = EstTran->SetValue(estimatedTransmission); + if ( !this->lResult.IsOK() ) {printLastError("Error setting estimatedTransmission!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + return SUCCESS; } + + int FLIR_SC65X::setMeasurementRange(int measRange) { - // with new FLIR CAMERAS range is 0-5 instead of 0-2 - if (measRange < 0 or measRange > 5) - { - printLastError( - "Error: measRange in setMeasurementRange must be in range 0-5!!!\n", 0); - return ERROR; - } - - printf("Try setting MeasurementRange to %d. REMEMBER to select the correct " - "focal lenght!"); - - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *currCase = - dynamic_cast(lDeviceParams->Get("CurrentCase")); - PvGenInteger *queryCase = - dynamic_cast(lDeviceParams->Get("QueryCase")); - PvGenFloat *lowLim = - dynamic_cast(lDeviceParams->Get("QueryCaseLowLimit")); - PvGenFloat *highLim = - dynamic_cast(lDeviceParams->Get("QueryCaseHighLimit")); - - PvGenBoolean *queryCaseEnabled = - dynamic_cast(lDeviceParams->Get("QueryCaseEnabled")); - - int64_t val = measRange; - - this->lResult = queryCase->SetValue(val); - if (!this->lResult.IsOK()) - { - printLastError("Error: case not defined in setMeasurementRange!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - usleep(3000); - this->lResult = currCase->SetValue(val); - if (!this->lResult.IsOK()) - { - printLastError("Error in setMeasurementRange!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - double limitLow, limitHigh = 0; - usleep(3000); - - this->lResult = lowLim->GetValue(limitLow); - if (!this->lResult.IsOK()) - { - printLastError("Error in low limit !!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - usleep(3000); - - this->lResult = highLim->GetValue(limitHigh); - if (!this->lResult.IsOK()) - { - printLastError("Error in high limit !!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + // with new FLIR CAMERAS range is 0-5 instead of 0-2 + if(measRange<0 or measRange>5) + { + printLastError("Error: measRange in setMeasurementRange must be in range 0-5!!!\n", 0); + return ERROR; + } + + printf("Try setting MeasurementRange to %d. REMEMBER to select the correct focal lenght!"); + + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *currCase = dynamic_cast( lDeviceParams->Get( "CurrentCase" ) ); + PvGenInteger *queryCase = dynamic_cast( lDeviceParams->Get( "QueryCase" ) ); + PvGenFloat *lowLim = dynamic_cast( lDeviceParams->Get( "QueryCaseLowLimit" ) ); + PvGenFloat *highLim = dynamic_cast( lDeviceParams->Get( "QueryCaseHighLimit" ) ); + + PvGenBoolean *queryCaseEnabled = dynamic_cast( lDeviceParams->Get( "QueryCaseEnabled" ) ); + + int64_t val = measRange; + + this->lResult = queryCase->SetValue(val); + if ( !this->lResult.IsOK() ) {printLastError("Error: case not defined in setMeasurementRange!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +usleep(3000); + this->lResult = currCase->SetValue(val); + if ( !this->lResult.IsOK() ) {printLastError("Error in setMeasurementRange!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + double limitLow, limitHigh = 0; +usleep(3000); + + this->lResult = lowLim->GetValue(limitLow); + if ( !this->lResult.IsOK() ) {printLastError("Error in low limit !!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +usleep(3000); + + this->lResult = highLim->GetValue(limitHigh); + if ( !this->lResult.IsOK() ) {printLastError("Error in high limit !!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + #ifdef debug - printf("Measurement range set to %.0f...%.0f\n", (limitLow - 273.15), - (limitHigh - 273.15)); + printf("Measurement range set to %.0f...%.0f\n",(limitLow-273.15) ,(limitHigh-273.15) ); #endif - return SUCCESS; + return SUCCESS; } + + int FLIR_SC65X::getFocusAbsPosition(int *focusPos) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lfocusPos = - dynamic_cast(lDeviceParams->Get("FocusPos")); - - int64_t val = 0; + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lfocusPos = dynamic_cast( lDeviceParams->Get( "FocusPos" ) ); - this->lResult = lfocusPos->GetValue(val); - if (!this->lResult.IsOK()) - { - printLastError("Error getting Focus Absolute Position\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + int64_t val = 0; - printf("getFocusAbsPosition val: %d\n", val); + this->lResult = lfocusPos->GetValue( val ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting Focus Absolute Position\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - *focusPos = val; + printf("getFocusAbsPosition val: %d\n", val); - return SUCCESS; + *focusPos=val; + + return SUCCESS; } + + int FLIR_SC65X::setFocusAbsPosition(int focusPos) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lfocusPos = - dynamic_cast(lDeviceParams->Get("FocusPos")); - PvGenInteger *lfocusSpeed = - dynamic_cast(lDeviceParams->Get("FocusSpeed")); - PvGenInteger *lfocusStep = - dynamic_cast(lDeviceParams->Get("FocusStep")); - PvGenCommand *lfocusIncrement = - dynamic_cast(lDeviceParams->Get("FocusIncrement")); - PvGenCommand *lfocusDecrement = - dynamic_cast(lDeviceParams->Get("FocusDecrement")); - - int64_t val = 0; - - this->lResult = lfocusPos->GetValue(val); - if (!this->lResult.IsOK()) - { - printLastError("Error getting Focus Absolute Position\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - this->lResult = lfocusSpeed->SetValue(1); // maybe not necessary - if (!this->lResult.IsOK()) - { - printLastError("Error setting focus speed\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - int currFocPos = (int)val; - int newFocPos = focusPos; - - this->lResult = - lfocusPos->SetValue(newFocPos); // set is not fine as read!!! maybe motor - // is not a step by step one. - if (!this->lResult.IsOK()) - { - printLastError("Error setting Focus Absolute Position\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - return SUCCESS; + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lfocusPos = dynamic_cast( lDeviceParams->Get( "FocusPos" ) ); + PvGenInteger *lfocusSpeed = dynamic_cast( lDeviceParams->Get( "FocusSpeed" ) ); + PvGenInteger *lfocusStep = dynamic_cast( lDeviceParams->Get( "FocusStep" ) ); + PvGenCommand *lfocusIncrement = dynamic_cast( lDeviceParams->Get( "FocusIncrement" ) ); + PvGenCommand *lfocusDecrement = dynamic_cast( lDeviceParams->Get( "FocusDecrement" ) ); + + int64_t val = 0; + + this->lResult = lfocusPos->GetValue( val ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting Focus Absolute Position\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + this->lResult = lfocusSpeed->SetValue(1); //maybe not necessary + if ( !this->lResult.IsOK() ) {printLastError("Error setting focus speed\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + int currFocPos = (int)val; + int newFocPos = focusPos; + + this->lResult = lfocusPos->SetValue( newFocPos ); //set is not fine as read!!! maybe motor is not a step by step one. + if ( !this->lResult.IsOK() ) {printLastError("Error setting Focus Absolute Position\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + return SUCCESS; } + + int FLIR_SC65X::executeAutoFocus() { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenCommand *autoFocus = - dynamic_cast(lDeviceParams->Get("AutoFocus")); - - this->lResult = autoFocus->Execute(); - if (!this->lResult.IsOK()) - { - printLastError("Error executing auto focus!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenCommand *autoFocus = dynamic_cast( lDeviceParams->Get( "AutoFocus" ) ); + + this->lResult = autoFocus->Execute(); + if ( !this->lResult.IsOK() ) {printLastError("Error executing auto focus!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} #ifdef debug - printf("AutoFocus Executed.\n"); + printf("AutoFocus Executed.\n"); #endif - return SUCCESS; + return SUCCESS; } -int FLIR_SC65X::setCalibMode(int calMode) // 0=off 1=automatic + + +int FLIR_SC65X::setCalibMode(int calMode) //0=off 1=automatic { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenEnum *calibMode = - dynamic_cast(lDeviceParams->Get("NUCMode")); + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenEnum *calibMode = dynamic_cast( lDeviceParams->Get( "NUCMode" ) ); + + this->lResult = calibMode->SetValue( calMode ); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting calibration mode!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - this->lResult = calibMode->SetValue(calMode); - if (!this->lResult.IsOK()) - { - printLastError("Error setting calibration mode!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + PvString lValue; + PvGenParameter *lGenParameter = lDeviceParams->Get( "NUCMode" ); + static_cast( lGenParameter )->GetValue( lValue ); - PvString lValue; - PvGenParameter *lGenParameter = lDeviceParams->Get("NUCMode"); - static_cast(lGenParameter)->GetValue(lValue); - this->autoCalibration = calMode; + this->autoCalibration = calMode; - printf("Calibration Mode set to: %s\n", lValue.GetAscii()); + printf( "Calibration Mode set to: %s\n", lValue.GetAscii() ); - return SUCCESS; + return SUCCESS; } + + int FLIR_SC65X::executeAutoCalib() { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenCommand *autoCalib = - dynamic_cast(lDeviceParams->Get("NUCAction")); - - this->lResult = autoCalib->Execute(); - if (!this->lResult.IsOK()) - { - printLastError("Error executing calibration!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenCommand *autoCalib = dynamic_cast( lDeviceParams->Get( "NUCAction" ) ); + + this->lResult = autoCalib->Execute(); + if ( !this->lResult.IsOK() ) {printLastError("Error executing calibration!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} #ifdef debug - printf("AutoCalibration Executed.\n"); + printf("AutoCalibration Executed.\n"); #endif - return SUCCESS; + return SUCCESS; } + + int FLIR_SC65X::startAcquisition(int *width, int *height, int *payloadSize) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lTLLocked = - dynamic_cast(lDeviceParams->Get("TLParamsLocked")); - PvGenInteger *lWidth = - dynamic_cast(lDeviceParams->Get("Width")); - PvGenInteger *lHeight = - dynamic_cast(lDeviceParams->Get("Height")); - PvGenInteger *lPayloadSize = - dynamic_cast(lDeviceParams->Get("PayloadSize")); - PvGenCommand *lResetTimestamp = dynamic_cast( - lDeviceParams->Get("GevTimestampControlReset")); - PvGenCommand *lStart = - dynamic_cast(lDeviceParams->Get("AcquisitionStart")); - // Get stream parameters/stats - // 17-10-2016: segmentation fault with SDK4. to check! - /* - PvGenParameterArray *lStreamParams = lStream->GetParameters(); - PvGenInteger *lCount = dynamic_cast( lStreamParams->Get( - "ImagesCount" ) ); PvGenFloat *lFrameRate = dynamic_cast( - lStreamParams->Get( "AcquisitionRateAverage" ) ); PvGenFloat *lBandwidth = - dynamic_cast( lStreamParams->Get( "BandwidthAverage" ) ); - */ - - PvGenInteger *lTickFreq = dynamic_cast( - lDeviceParams->Get("GevTimestampTickFrequency")); - this->lResult = lTickFreq->GetValue(tickFreq); - if (!this->lResult.IsOK()) - { - printLastError("Error getting GevTimestampTickFrequency in " - "startAcquisition!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - } - // printf("---> GevTimestampTickFrequency = %d\n", tickFreq); - - int64_t w = 0; - int64_t h = 0; - int64_t lSize = 0; - - this->lResult = lWidth->GetValue(w); - if (!this->lResult.IsOK()) - { - printLastError("Error getting frame width in startAcquisition!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - this->lResult = lHeight->GetValue(h); - if (!this->lResult.IsOK()) - { - printLastError("Error getting frame height in startAcquisition!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - this->lResult = lPayloadSize->GetValue(lSize); - if (!this->lResult.IsOK()) - { - printLastError("Error getting payload size in startAcquisition!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - this->width = *width = (int)w; - this->height = *height = (int)h - 3; // first 3 rows are metadata - - *payloadSize = lSize; // payload = width*height*2 + metadata - - /* - new 09 mar 2016 for SDK4 - // If this is a GigE Vision device, configure GigE Vision specific streaming - parameters - */ - PvDeviceGEV *lDeviceGEV = static_cast(this->lDevice); - // 17-10-2016 lStreamGEV moved down - /* - end new - */ - - // Negotiate streaming packet size - // this->lResult = lDevice->NegotiatePacketSize(); //SDK 3 - this->lResult = lDeviceGEV->NegotiatePacketSize(); // SDK 4 - if (!this->lResult.IsOK()) - { - printLastError( - "Error negotiating packet size in start acquisition!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - PvGenInteger *lPacketSize = dynamic_cast( - lDevice->GetParameters()->Get("GevSCPSPacketSize")); - - int64_t lPacketSizeValue = 0; - lResult = lPacketSize->GetValue(lPacketSizeValue); - if (!lResult.IsOK()) - { - printLastError("FATAL ERROR: Unable to read packet size!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - // fprintf( stderr, "FATAL ERROR: Unable to read packet size\n" ); - } - printf("--------> lPacketSizeValue %d\n", lPacketSizeValue); - - // Open stream - // this->lResult = this->lStream->Open( this->ipAddress); //SDK 3 - this->lStream = - PvStream::CreateAndOpen(this->ipAddress, &this->lResult); // 20160309 SDK4 - if ((this->lStream == NULL) || !this->lResult.IsOK()) - { - printLastError("Error opening stream in start acquisition!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - PvStream::Free(this->lStream); - return ERROR; - } - - // Use min of BUFFER_COUNT and how many buffers can be queued in PvStream - uint32_t lBufferCount = (lStream->GetQueuedBufferMaximum() < BUFFER_COUNT) - ? lStream->GetQueuedBufferMaximum() - : BUFFER_COUNT; - - // new 17-10-2016 for SDK4 - // If this is a GigE Vision device, configure GigE Vision specific streaming - // parameters - PvStreamGEV *lStreamGEV = static_cast(this->lStream); - - if (this->lStream->IsOpen()) - { - // printf("lStream OPEN Local Port %d \n", lStream->GetLocalPort() ); //SDK - // 3 - printf("lStream OPEN Local Port %u \n", - lStreamGEV->GetLocalPort()); // SDK 4 not working.... segmentation - // fault to check! - } - else - { - printf("lStream NOT OPEN\n"); - } - if (lDevice->IsConnected()) - { - printf("PvDevice connect \n"); - } - else - { - printf("PvDevice not connect \n"); - } - - printf("----------> Buffer count %d lSize %d \n", lBufferCount, lSize); - - // Create, alloc buffers - this->lBuffers = new PvBuffer[lBufferCount]; - for (uint32_t i = 0; i < lBufferCount; i++) - { - lResult = lBuffers[i].Alloc(static_cast(lSize)); - if (!lResult.IsOK()) - printf("Error memory buffer allocation %d !!!\n(%s)\n", (i + 1), - lResult.GetDescription().GetAscii()); - } - - if (lStream->IsOpen()) - printf("lStream OPEN\n"); - else - printf("lStream NOT OPEN\n"); - - if (lDevice->IsConnected()) - printf("PvDevice connect \n"); - else - printf("PvDevice not connect \n"); - - // Have to set the Device IP destination to the Stream - // this->lResult = lDevice->SetStreamDestination( - // lStream->GetLocalIPAddress(), lStream->GetLocalPort() ); //SDK 3 - this->lResult = lDeviceGEV->SetStreamDestination( - lStreamGEV->GetLocalIPAddress(), - lStreamGEV->GetLocalPort()); // SDK 4 - 9 mar 2016 - if (!this->lResult.IsOK()) - { - printLastError("Error setting stream dest. in start acquisition!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - if (lStream->IsOpen()) - printf("lStream OPEN\n"); - else - printf("lStream NOT OPEN\n"); - - if (lDevice->IsConnected()) - printf("PvDevice connect \n"); - else - printf("PvDevice not connect \n"); - - // Queue all buffers in the stream - for (uint32_t i = 0; i < lBufferCount; i++) - { - printf("------------------------ Queuing Buffer " - "-----------------------------------\n"); - lResult = lStream->QueueBuffer(&lBuffers[i]); - printf("------------------------ Queued Buffer " - "-----------------------------------\n"); - if (!lResult.IsPending()) - printf("Error buffer enqueue %d !!!\n(%s, %s)\n", (i + 1), - lResult.GetDescription().GetAscii(), - lResult.GetCodeString().GetAscii()); - } - - if (lStream->IsOpen()) - printf("lStream OPEN\n"); - else - printf("lStream NOT OPEN\n"); - - if (lDevice->IsConnected()) - printf("PvDevice connect \n"); - else - printf("PvDevice not connect \n"); - - // TLParamsLocked is optional but when present, it MUST be set to 1 - // before sending the AcquisitionStart command - if (lTLLocked != NULL) - { - usleep(3000); - this->lResult = lTLLocked->SetValue(1); - - if (!this->lResult.IsOK()) + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lTLLocked = dynamic_cast( lDeviceParams->Get( "TLParamsLocked" ) ); + PvGenInteger *lWidth = dynamic_cast( lDeviceParams->Get( "Width" ) ); + PvGenInteger *lHeight = dynamic_cast( lDeviceParams->Get( "Height" ) ); + PvGenInteger *lPayloadSize = dynamic_cast( lDeviceParams->Get( "PayloadSize" ) ); + PvGenCommand *lResetTimestamp = dynamic_cast( lDeviceParams->Get( "GevTimestampControlReset" ) ); + PvGenCommand *lStart = dynamic_cast( lDeviceParams->Get( "AcquisitionStart" ) ); + // Get stream parameters/stats +//17-10-2016: segmentation fault with SDK4. to check! +/* + PvGenParameterArray *lStreamParams = lStream->GetParameters(); + PvGenInteger *lCount = dynamic_cast( lStreamParams->Get( "ImagesCount" ) ); + PvGenFloat *lFrameRate = dynamic_cast( lStreamParams->Get( "AcquisitionRateAverage" ) ); + PvGenFloat *lBandwidth = dynamic_cast( lStreamParams->Get( "BandwidthAverage" ) ); +*/ + + + PvGenInteger *lTickFreq = dynamic_cast( lDeviceParams->Get( "GevTimestampTickFrequency" ) ); + this->lResult = lTickFreq->GetValue( tickFreq ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting GevTimestampTickFrequency in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() );} + //printf("---> GevTimestampTickFrequency = %d\n", tickFreq); + + int64_t w = 0; + int64_t h = 0; + int64_t lSize = 0; + + this->lResult = lWidth->GetValue( w ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting frame width in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + this->lResult = lHeight->GetValue( h ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting frame height in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + this->lResult = lPayloadSize->GetValue( lSize ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting payload size in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + this->width = *width = (int)w; + this->height = *height= (int)h-3; //first 3 rows are metadata + + *payloadSize=lSize; //payload = width*height*2 + metadata + + +/* + new 09 mar 2016 for SDK4 + // If this is a GigE Vision device, configure GigE Vision specific streaming parameters +*/ + PvDeviceGEV *lDeviceGEV = static_cast( this->lDevice ); + //17-10-2016 lStreamGEV moved down +/* +end new +*/ + + // Negotiate streaming packet size + //this->lResult = lDevice->NegotiatePacketSize(); //SDK 3 + this->lResult = lDeviceGEV->NegotiatePacketSize(); //SDK 4 + if ( !this->lResult.IsOK() ) + { + printLastError("Error negotiating packet size in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + return ERROR; + } + + + PvGenInteger *lPacketSize = dynamic_cast( lDevice->GetParameters()->Get( "GevSCPSPacketSize" ) ); + + int64_t lPacketSizeValue = 0; + lResult = lPacketSize->GetValue( lPacketSizeValue ); + if ( !lResult.IsOK() ) { - printLastError("Error setting TLParamsLocked to 1!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; + printLastError("FATAL ERROR: Unable to read packet size!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + return ERROR; + //fprintf( stderr, "FATAL ERROR: Unable to read packet size\n" ); + } + printf("--------> lPacketSizeValue %d\n", lPacketSizeValue); + + // Open stream + //this->lResult = this->lStream->Open( this->ipAddress); //SDK 3 + this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); //20160309 SDK4 + if ( ( this->lStream == NULL ) || !this->lResult.IsOK() ) + { + printLastError("Error opening stream in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + PvStream::Free( this->lStream ); + return ERROR; + } + + // Use min of BUFFER_COUNT and how many buffers can be queued in PvStream + uint32_t lBufferCount = ( lStream->GetQueuedBufferMaximum() < BUFFER_COUNT ) ? + lStream->GetQueuedBufferMaximum() : + BUFFER_COUNT; + + //new 17-10-2016 for SDK4 + // If this is a GigE Vision device, configure GigE Vision specific streaming parameters + PvStreamGEV *lStreamGEV = static_cast( this->lStream ); + + if( this->lStream->IsOpen() ) + { + //printf("lStream OPEN Local Port %d \n", lStream->GetLocalPort() ); //SDK 3 + printf("lStream OPEN Local Port %u \n", lStreamGEV->GetLocalPort() ); //SDK 4 not working.... segmentation fault to check! + } + else + { + printf("lStream NOT OPEN\n"); + } + if(lDevice->IsConnected()) + {printf( "PvDevice connect \n");} + else + {printf( "PvDevice not connect \n");} + + + printf("----------> Buffer count %d lSize %d \n", lBufferCount, lSize); + + // Create, alloc buffers + this->lBuffers = new PvBuffer[ lBufferCount ]; + for ( uint32_t i = 0; i < lBufferCount; i++ ) + { + lResult = lBuffers[ i ].Alloc( static_cast( lSize ) ); + if ( !lResult.IsOK() ) + printf("Error memory buffer allocation %d !!!\n(%s)\n", (i+1) , lResult.GetDescription().GetAscii() ); + } + + if( lStream->IsOpen() ) printf("lStream OPEN\n"); + else printf("lStream NOT OPEN\n"); + + if(lDevice->IsConnected()) + printf( "PvDevice connect \n"); + else + printf( "PvDevice not connect \n"); + + // Have to set the Device IP destination to the Stream + //this->lResult = lDevice->SetStreamDestination( lStream->GetLocalIPAddress(), lStream->GetLocalPort() ); //SDK 3 + this->lResult = lDeviceGEV->SetStreamDestination( lStreamGEV->GetLocalIPAddress(), lStreamGEV->GetLocalPort() ); //SDK 4 - 9 mar 2016 + if ( !this->lResult.IsOK() ) {printLastError("Error setting stream dest. in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + if( lStream->IsOpen() ) printf("lStream OPEN\n"); + else printf("lStream NOT OPEN\n"); + + if(lDevice->IsConnected()) + printf( "PvDevice connect \n"); + else + printf( "PvDevice not connect \n"); + + + // Queue all buffers in the stream + for ( uint32_t i = 0; i < lBufferCount; i++ ) + { +printf("------------------------ Queuing Buffer -----------------------------------\n"); + lResult = lStream->QueueBuffer( &lBuffers[i] ); +printf("------------------------ Queued Buffer -----------------------------------\n"); + if ( !lResult.IsPending() ) + printf("Error buffer enqueue %d !!!\n(%s, %s)\n", (i+1) , lResult.GetDescription().GetAscii(), lResult.GetCodeString().GetAscii() ); } - } - - // reset timestamp counter - this->lResult = lResetTimestamp->Execute(); - if (!this->lResult.IsOK()) - { - printLastError("Error resetting timestamp counter!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - // Tell the device to start sending images - this->lResult = lStart->Execute(); - if (!this->lResult.IsOK()) - { - printLastError( - "Error sending StartAcquisition command to device!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - // debug - triggered = 0; - /* - printf( "Get Local IP Address %s \n", - lStream->GetLocalIPAddress().GetAscii() ); printf( "QueuedBuffer %d \n", - lStream->GetQueuedBufferCount() ); printf( "QueuedBuffer Maximum %d \n", - lStream->GetQueuedBufferMaximum() ); - - - if(lDevice->IsConnected()) - printf( "PvDevice connect \n"); - else - printf( "PvDevice not connect \n"); - - - if(lStream->IsOpen()) - printf( "PvStream open \n"); - else - printf( "PvStream not open \n"); - */ - - return SUCCESS; + + if( lStream->IsOpen() ) printf("lStream OPEN\n"); + else printf("lStream NOT OPEN\n"); + + if(lDevice->IsConnected()) + printf( "PvDevice connect \n"); + else + printf( "PvDevice not connect \n"); + + // TLParamsLocked is optional but when present, it MUST be set to 1 + // before sending the AcquisitionStart command + if ( lTLLocked != NULL ) + { +usleep(3000); + this->lResult = lTLLocked->SetValue( 1 ); + + if ( !this->lResult.IsOK() ) {printLastError("Error setting TLParamsLocked to 1!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + } + + //reset timestamp counter + this->lResult = lResetTimestamp->Execute(); + if ( !this->lResult.IsOK() ) {printLastError("Error resetting timestamp counter!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + // Tell the device to start sending images + this->lResult = lStart->Execute(); + if ( !this->lResult.IsOK() ) {printLastError("Error sending StartAcquisition command to device!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +//debug + triggered = 0; +/* + printf( "Get Local IP Address %s \n", lStream->GetLocalIPAddress().GetAscii() ); + printf( "QueuedBuffer %d \n", lStream->GetQueuedBufferCount() ); + printf( "QueuedBuffer Maximum %d \n", lStream->GetQueuedBufferMaximum() ); + + + if(lDevice->IsConnected()) + printf( "PvDevice connect \n"); + else + printf( "PvDevice not connect \n"); + + + if(lStream->IsOpen()) + printf( "PvStream open \n"); + else + printf( "PvStream not open \n"); +*/ + + return SUCCESS; } + + int FLIR_SC65X::stopAcquisition() { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lTLLocked = - dynamic_cast(lDeviceParams->Get("TLParamsLocked")); - PvGenCommand *lStop = - dynamic_cast(lDeviceParams->Get("AcquisitionStop")); - - // Tell the device to stop sending images - this->lResult = lStop->Execute(); - if (!this->lResult.IsOK()) - { - printLastError( - "Error sending AcquisitionStop command to the device!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; - } - - // If present reset TLParamsLocked to 0. Must be done AFTER the - // streaming has been stopped - if (lTLLocked != NULL) - { - this->lResult = lTLLocked->SetValue(0); - if (!this->lResult.IsOK()) + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lTLLocked = dynamic_cast( lDeviceParams->Get( "TLParamsLocked" ) ); + PvGenCommand *lStop = dynamic_cast( lDeviceParams->Get( "AcquisitionStop" ) ); + + // Tell the device to stop sending images + this->lResult = lStop->Execute(); + if ( !this->lResult.IsOK() ) {printLastError("Error sending AcquisitionStop command to the device!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + // If present reset TLParamsLocked to 0. Must be done AFTER the + // streaming has been stopped + if ( lTLLocked != NULL ) { - printLastError("Error resetting TLParamsLocked to 0!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - return ERROR; + this->lResult = lTLLocked->SetValue( 0 ); + if ( !this->lResult.IsOK() ) {printLastError("Error resetting TLParamsLocked to 0!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} } - } - // printf( "Aborting buffers still in stream\n" ); - lStream->AbortQueuedBuffers(); - while (lStream->GetQueuedBufferCount() > 0) - { - PvBuffer *lBuffer = NULL; - PvResult lOperationResult; - lStream->RetrieveBuffer(&lBuffer, &lOperationResult); - // printf( " Post-abort retrieved buffer: %s\n", - // lOperationResult.GetCodeString().GetAscii() ); - } + //printf( "Aborting buffers still in stream\n" ); + lStream->AbortQueuedBuffers(); + while ( lStream->GetQueuedBufferCount() > 0 ) + { + PvBuffer *lBuffer = NULL; + PvResult lOperationResult; + lStream->RetrieveBuffer( &lBuffer, &lOperationResult ); + //printf( " Post-abort retrieved buffer: %s\n", lOperationResult.GetCodeString().GetAscii() ); + } + + //printf( "Releasing buffers\n" ); + delete []lBuffers; - // printf( "Releasing buffers\n" ); - delete[] lBuffers; + // Now close the stream. Also optionnal but nice to have + printf( "Closing stream\n" ); + lStream->Close(); - // Now close the stream. Also optionnal but nice to have - printf("Closing stream\n"); - lStream->Close(); - return SUCCESS; + return SUCCESS; } + int FLIR_SC65X::getFrame(int *status, void *frame, void *metaData) { - // status=1 complete # status=2 incomplete # status=3 timeout # status=4 - // triggered frame + complete - // char lDoodle[] = "|\\-|-/"; - // static int lDoodleIndex = 0; - int64_t lImageCountVal = 0; - double lFrameRateVal = 0.0; - double lBandwidthVal = 0.0; - - PvBuffer *lBuffer = NULL; - PvResult lOperationResult; - - // Get stream parameters/stats - PvGenParameterArray *lStreamParams = lStream->GetParameters(); - PvGenInteger *lCount = - dynamic_cast(lStreamParams->Get("ImagesCount")); - PvGenFloat *lFrameRate = - dynamic_cast(lStreamParams->Get("AcquisitionRateAverage")); - PvGenFloat *lBandwidth = - dynamic_cast(lStreamParams->Get("BandwidthAverage")); - - *status = 2; // frame incomplete by default - // ++lDoodleIndex %= 6; - - // Retrieve next buffer - this->lResult = lStream->RetrieveBuffer(&lBuffer, &lOperationResult, 1000); - - // this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult); - if (this->lResult.IsOK()) - { - if (lOperationResult.IsOK()) +//status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete + // char lDoodle[] = "|\\-|-/"; + // static int lDoodleIndex = 0; + int64_t lImageCountVal = 0; + double lFrameRateVal = 0.0; + double lBandwidthVal = 0.0; + + PvBuffer *lBuffer = NULL; + PvResult lOperationResult; + + // Get stream parameters/stats + PvGenParameterArray *lStreamParams = lStream->GetParameters(); + PvGenInteger *lCount = dynamic_cast( lStreamParams->Get( "ImagesCount" ) ); + PvGenFloat *lFrameRate = dynamic_cast( lStreamParams->Get( "AcquisitionRateAverage" ) ); + PvGenFloat *lBandwidth = dynamic_cast( lStreamParams->Get( "BandwidthAverage" ) ); + + *status=2; //frame incomplete by default + // ++lDoodleIndex %= 6; + + // Retrieve next buffer + this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, 1000 ); + + //this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult); + if ( this->lResult.IsOK() ) { - // lCount->GetValue( lImageCountVal ); //comment out 17-10-2016 with SDK4 - // segmentation fault - lFrameRate->GetValue(lFrameRateVal); - lBandwidth->GetValue(lBandwidthVal); - - // If the buffer contains an image, display width and height - uint32_t lWidth = 0, lHeight = 0; - if (lBuffer->GetPayloadType() == PvPayloadTypeImage) - { - // Get image specific buffer interface - PvImage *lImage = lBuffer->GetImage(); - // Read width, height - lWidth = lImage->GetWidth(); - lHeight = lImage->GetHeight(); - currTime = lBuffer->GetTimestamp(); - - currIdx = lBuffer->GetBlockID(); - // if( triggered && currIdx != lastIdx+1) - // if( triggered) - // printf("deltaTime ms = %f idx %d tick %d\n", ( ((currTime - - //lastTime) *.1) / tickFreq) * 1000 , currIdx, tickFreq ); - lastTime = currTime; - lastIdx = currIdx; - /* - printf( "%c Timestamp: %016llX BlockID: - %04X W: %i H: %i %.01f FPS %.01f Mb/s\r", lDoodle[ lDoodleIndex ], - lBuffer->GetTimestamp(), - lBuffer->GetBlockID(), - lWidth, - lHeight, - lFrameRateVal, - lBandwidthVal / 1000000.0 ); - */ - unsigned int width = lWidth; - unsigned int height = lHeight; - - // PvUInt8* dataPtr = lImage->GetDataPointer(); //NO!!!! - // PvUInt8* dataPtr = lBuffer->GetDataPointer(); //OK for - //SDK3 - uint8_t *dataPtr = lBuffer->GetDataPointer(); // 8 mar 2016 for SDK4 - - // last 3 rows of the frame are metadata - memcpy(frame, (unsigned char *)dataPtr, width * 2 * (height - 3)); - memcpy(metaData, (unsigned char *)dataPtr + (width * 2 * (height - 3)), - width * 2 * 3); - - *status = 1; // complete - - FPGA_HEADER *pFPGA; - pFPGA = (FPGA_HEADER *)metaData; - - // if(pFPGA->dp1_trig_state) //NOT WORK!!!!!!!!!! - if (pFPGA->dp1_trig_type & FPGA_TRIG_TYPE_MARK) // correct way :-) - { - // printf("\nTrigger dp1_trig_state %d \n", pFPGA->dp1_trig_state); - // printf("\nTrigger dp1_trig_type %d \n", pFPGA->dp1_trig_type); - printf("External trigger!\n"); - *status = 4; // complete + triggered! - triggered = 1; + if(lOperationResult.IsOK()) + { + //lCount->GetValue( lImageCountVal ); //comment out 17-10-2016 with SDK4 segmentation fault + lFrameRate->GetValue( lFrameRateVal ); + lBandwidth->GetValue( lBandwidthVal ); + + // If the buffer contains an image, display width and height + uint32_t lWidth = 0, lHeight = 0; + if ( lBuffer->GetPayloadType() == PvPayloadTypeImage ) + { + // Get image specific buffer interface + PvImage *lImage = lBuffer->GetImage(); + // Read width, height + lWidth = lImage->GetWidth(); + lHeight = lImage->GetHeight(); + currTime = lBuffer->GetTimestamp(); + + currIdx = lBuffer->GetBlockID(); + //if( triggered && currIdx != lastIdx+1) + //if( triggered) + // printf("deltaTime ms = %f idx %d tick %d\n", ( ((currTime - lastTime) *.1) / tickFreq) * 1000 , currIdx, tickFreq ); + lastTime = currTime; + lastIdx = currIdx; +/* + printf( "%c Timestamp: %016llX BlockID: %04X W: %i H: %i %.01f FPS %.01f Mb/s\r", + lDoodle[ lDoodleIndex ], + lBuffer->GetTimestamp(), + lBuffer->GetBlockID(), + lWidth, + lHeight, + lFrameRateVal, + lBandwidthVal / 1000000.0 ); +*/ + unsigned int width = lWidth; + unsigned int height = lHeight; + + // PvUInt8* dataPtr = lImage->GetDataPointer(); //NO!!!! + // PvUInt8* dataPtr = lBuffer->GetDataPointer(); //OK for SDK3 + uint8_t* dataPtr = lBuffer->GetDataPointer(); //8 mar 2016 for SDK4 + + //last 3 rows of the frame are metadata + memcpy( frame , (unsigned char *)dataPtr, width*2*(height-3) ); + memcpy( metaData , (unsigned char *)dataPtr+(width*2*(height-3)), width*2*3 ); + + *status=1; //complete + + FPGA_HEADER* pFPGA; + pFPGA = (FPGA_HEADER*)metaData; + + //if(pFPGA->dp1_trig_state) //NOT WORK!!!!!!!!!! + if(pFPGA->dp1_trig_type & FPGA_TRIG_TYPE_MARK) //correct way :-) + { + //printf("\nTrigger dp1_trig_state %d \n", pFPGA->dp1_trig_state); + //printf("\nTrigger dp1_trig_type %d \n", pFPGA->dp1_trig_type); + printf("External trigger!\n"); + *status=4; //complete + triggered! + triggered = 1; + } + } } - } + else //new 28 agosto 2012 + { + *status=2; //incomplete + //printf( "%c Incomplete\r", lDoodle[ lDoodleIndex ] ); + printf("%s %d\n", lOperationResult.GetCodeString().GetAscii(), lBuffer->GetPayloadType() ); + incompleteFrame++; + } + // We have an image - do some processing (...) and VERY IMPORTANT, + // re-queue the buffer in the stream object + lStream->QueueBuffer( lBuffer ); + return SUCCESS; } - else // new 28 agosto 2012 - { - *status = 2; // incomplete - // printf( "%c Incomplete\r", lDoodle[ lDoodleIndex ] ); - printf("%s %d\n", lOperationResult.GetCodeString().GetAscii(), - lBuffer->GetPayloadType()); - incompleteFrame++; + else// Timeout + { + printf("%s (%s) \n", lResult.GetCodeString().GetAscii(), lResult.GetDescription().GetAscii() ); + printLastError("Error reading frame!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + *status=3; //timeout +// printf( "%c Timeout\r", lDoodle[ lDoodleIndex ] ); + return ERROR; } - // We have an image - do some processing (...) and VERY IMPORTANT, - // re-queue the buffer in the stream object - lStream->QueueBuffer(lBuffer); - return SUCCESS; - } - else // Timeout - { - printf("%s (%s) \n", lResult.GetCodeString().GetAscii(), - lResult.GetDescription().GetAscii()); - printLastError("Error reading frame!!!\n(%s)\n", - lResult.GetDescription().GetAscii()); - *status = 3; // timeout - // printf( "%c Timeout\r", lDoodle[ lDoodleIndex ] ); - return ERROR; - } -} -// Convert frame pixels from Kelvin to Celsius -int FLIR_SC65X::frameConv(unsigned short *frame, int width, int height) -{ - short sub = 0; - switch (irFrameFormat) - { - case linear100mK: - sub = 2731; // 1 = 100mK = 100mC -> precisione decimo di grado - break; - case linear10mK: - sub = 27315; // 1 = 10mK = 10mC -> precisione centesimo di grado - break; - } - - for (int i = 0; i < width * height; i++) - { - frame[i] = frame[i] - sub; - } - - return SUCCESS; } -int FLIR_SC65X::setStreamingMode(IRFMT_ENUM irFormat, int streamingEnabled, - bool autoAdjustLimit, - const char *streamingServer, int streamingPort, - unsigned int lowLim, unsigned int highLim, - int adjRoiX, int adjRoiY, int adjRoiW, - int adjRoiH, const char *deviceName) -{ - this->streamingEnabled = streamingEnabled; - if (streamingEnabled) - { - memcpy(this->streamingServer, streamingServer, strlen(streamingServer) + 1); - memcpy(this->deviceName, deviceName, strlen(deviceName) + 1); - this->streamingPort = streamingPort; - this->autoAdjustLimit = autoAdjustLimit; - // for FLIR 655 - // unsigned int minLim = 2000; // 200 K or -73 deg Celsius - // unsigned int maxLim = 62000; // 6200 K or 5927 deg Celsius - switch (irFormat) +//Convert frame pixels from Kelvin to Celsius +int FLIR_SC65X::frameConv(unsigned short *frame, int width, int height) +{ + short sub=0; + switch(irFrameFormat) + { + case linear100mK: sub=2731; //1 = 100mK = 100mC -> precisione decimo di grado + break; + case linear10mK: sub=27315; //1 = 10mK = 10mC -> precisione centesimo di grado + break; + } + + for(int i=0; ilowLim = - lowLim * 10; // 20170918: streaming is already converted in - // temperature. Radiometric frames are never send. - this->highLim = highLim * 10; - minLim = 0; - maxLim = 62000 - 27315; // 3468.5°C - break; - case linear100mK: - this->lowLim = lowLim * 10; - this->highLim = highLim * 10; - minLim = 0; - maxLim = 62000 - 27315; // 3468.5°C - break; - case linear10mK: - this->lowLim = lowLim * 100; - this->highLim = highLim * 100; - minLim = 0; - maxLim = 62000 - 27315; // 346.85°C - break; + frame[i] = frame[i] - sub; } + + return SUCCESS; - this->adjRoiX = adjRoiX; - this->adjRoiY = adjRoiY; - this->adjRoiW = adjRoiW; - this->adjRoiH = adjRoiH; - } - else - { - printf("Streaming DISABLED\n"); - } - return SUCCESS; } -int FLIR_SC65X::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) +int FLIR_SC65X::setStreamingMode( IRFMT_ENUM irFormat, int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) +{ + this->streamingEnabled = streamingEnabled; + + if( streamingEnabled ) + { + memcpy( this->streamingServer, streamingServer, strlen(streamingServer)+1 ); + memcpy( this->deviceName, deviceName, strlen(deviceName)+1 ); + this->streamingPort = streamingPort; + this->autoAdjustLimit = autoAdjustLimit; + + //for FLIR 655 + //unsigned int minLim = 2000; // 200 K or -73 deg Celsius + //unsigned int maxLim = 62000; // 6200 K or 5927 deg Celsius + + switch(irFormat) + { + case radiometric: + this->lowLim = lowLim * 10; //20170918: streaming is already converted in temperature. Radiometric frames are never send. + this->highLim = highLim * 10; + minLim= 0; + maxLim= 62000-27315; //3468.5°C + break; + case linear100mK: + this->lowLim = lowLim * 10; + this->highLim = highLim * 10; + minLim= 0; + maxLim= 62000-27315; //3468.5°C + break; + case linear10mK: + this->lowLim = lowLim * 100; + this->highLim = highLim * 100; + minLim= 0; + maxLim= 62000-27315; //346.85°C + break; + } + + this->adjRoiX = adjRoiX; + this->adjRoiY = adjRoiY; + this->adjRoiW = adjRoiW; + this->adjRoiH = adjRoiH; + + } + else + { + printf("Streaming DISABLED\n"); + } + return SUCCESS; +} + + +int FLIR_SC65X::setAcquisitionMode( int storeEnabled , int acqSkipFrameNumber) { - this->storeEnabled = storeEnabled; - this->acqSkipFrameNumber = acqSkipFrameNumber; - return SUCCESS; + this->storeEnabled = storeEnabled; + this->acqSkipFrameNumber = acqSkipFrameNumber; + return SUCCESS; } -int FLIR_SC65X::setTriggerMode(int triggerMode, double burstDuration, - int numTrigger) +int FLIR_SC65X::setTriggerMode( int triggerMode, double burstDuration, int numTrigger ) { - this->triggerMode = triggerMode; - this->burstDuration = burstDuration; - this->numTrigger = numTrigger; + this->triggerMode = triggerMode; + this->burstDuration = burstDuration; + this->numTrigger = numTrigger; - return setExposureMode((EXPMODE_ENUM)triggerMode); + return setExposureMode((EXPMODE_ENUM) triggerMode); } int FLIR_SC65X::softwareTrigger() { - this->startStoreTrg = 1; - return SUCCESS; + this->startStoreTrg = 1; + return SUCCESS; } -int FLIR_SC65X::setTreeInfo(void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid) +int FLIR_SC65X::setTreeInfo( void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) { - this->treePtr = treePtr; - this->framesNid = framesNid; - this->timebaseNid = timebaseNid; - this->framesMetadNid = framesMetadNid; - this->frame0TimeNid = frame0TimeNid; + this->treePtr = treePtr ; + this->framesNid = framesNid; + this->timebaseNid = timebaseNid; + this->framesMetadNid = framesMetadNid; + this->frame0TimeNid = frame0TimeNid; - return SUCCESS; + return SUCCESS; } + void FLIR_SC65X::printLastError(const char *format, const char *msg) { - error[0] = 0; - if (msg) - sprintf(error, format, msg); - else - sprintf(error, format); + error[0] = 0; + if(msg) + sprintf(error, format, msg); + else + sprintf(error, format); } + void FLIR_SC65X::getLastError(char *msg) { - sprintf(msg, "%s", (error[0] == 0) ? "" : error); + sprintf(msg, "%s", (error[0]==0) ? "" : error); } int FLIR_SC65X::stopFramesAcquisition() { - int count = 0; - - if (acqFlag == 0) - return SUCCESS; - - acqStopped = 0; - acqFlag = 0; - while (!acqStopped & count < 10) - { - count++; - usleep(50000); // 20190829 FM: 5000->50000 - } - - if (count == 10) - { - printLastError("Cannot stop acquisition loop", 0); - return ERROR; - } - - return SUCCESS; + int count = 0; + + if (acqFlag == 0) + return SUCCESS; + + acqStopped = 0; + acqFlag = 0; + while( !acqStopped & count < 10 ) + { + count++; + usleep(50000); //20190829 FM: 5000->50000 + } + + if(count == 10) + { + printLastError("Cannot stop acquisition loop", 0); + return ERROR; + } + + + return SUCCESS; } int FLIR_SC65X::startFramesAcquisition() { - int frameTriggerCounter; - int frameCounter; - int frameStatus; - // int startStoreTrg = 0; //moved outside to let the device call the - //softwareTrigger() function - int NtriggerCount = 0; - int burstNframe; - int rstatus; - int tcpStreamHandle = -1; - int metaSize; - int savedFrameNumber; - - float frameTime = 0.0; - - void *saveList; - void *streamingList; - - short *frameBuffer; - short *metaData; - unsigned char *frame8bit; - - struct timeval tv; // manage frame timestamp in internal mode - int64_t timeStamp; - int64_t timeStamp0; - - TreeNode *t0Node; - try - { - t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); - Data *nodeData = t0Node->getData(); - timeStamp0 = (int64_t)nodeData->getLong(); - } - catch (const MdsException &exc) - { - printf("Error getting frame0 time\n"); - } - - frameBuffer = (short *)calloc(1, width * height * sizeof(short)); - frame8bit = (unsigned char *)calloc(1, width * height * sizeof(char)); - - metaSize = width * 3 * sizeof(short); - metaData = (short *)calloc(1, metaSize); - - camStartSave(&saveList); // # Initialize save frame Linked list reference - - camStartStreaming( - &streamingList); // # Initialize streaming frame Linked list reference - - burstNframe = (int)(burstDuration * frameRate + 1); - - acqFlag = 1; - frameTriggerCounter = 0; - frameCounter = 0; - incompleteFrame = 0; - savedFrameNumber = 0; - - startStoreTrg = 0; // manage the mdsplus saving process. SAVE always start - // with a SW or HW trigger. (0=no-save; 1=save) - - while (acqFlag) - { - getFrame(&frameStatus, frameBuffer, metaData); // get the frame - - if (storeEnabled) - { - if (triggerMode == 1) // External trigger source - { - - if ((frameStatus == 4) && - (startStoreTrg == 0)) // start data storing @ 1st trigger seen - // (trigger is on image header!) + int frameTriggerCounter; + int frameCounter; + int frameStatus; +// int startStoreTrg = 0; //moved outside to let the device call the softwareTrigger() function + int NtriggerCount = 0; + int burstNframe; + int rstatus; + int tcpStreamHandle = -1; + int metaSize; + int savedFrameNumber; + + float frameTime = 0.0; + float timeOffset = 0.0; //20210325 + + void *saveList; + void *streamingList; + + short *frameBuffer; + short *metaData; + unsigned char *frame8bit; + + struct timeval tv; //manage frame timestamp in internal mode + int64_t timeStamp; + int64_t timeStamp0; + + TreeNode *t0Node; + try{ + t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); + Data *nodeData = t0Node->getData(); + timeStamp0 = (int64_t)nodeData->getLong(); + }catch(MdsException *exc) { - startStoreTrg = 1; - printf("TRIGGERED:\n"); + printf("Error getting frame0 time\n"); } - if (frameTriggerCounter == burstNframe) - { - triggered = 0; - startStoreTrg = 0; // disable storing - NtriggerCount++; - - printf("ACQUIRED ALL FRAMES %d FOR TRIGGER : %d\n", - frameTriggerCounter - 1, NtriggerCount); - frameTriggerCounter = 0; - if (autoCalibration) // execute calibration action @ every burst of - // frames (only if NO auto calibration) + //if ( triggerMode != 1 ) //in internal mode use the timebaseNid as T0 offset (ex. T_START_SPIDER) + { //20210325: In external trigger, triggered on event must be set timeOffest + TreeNode *tStartOffset; + try{ + tStartOffset = new TreeNode(timebaseNid, (Tree *)treePtr); + Data *nodeData = tStartOffset->getData(); + timeOffset = (float)nodeData->getFloatArray()[0]; + }catch(MdsException *exc) { - executeAutoCalib(); + sprintf(error, "%s: Error getting timebaseNid (offset time set to 0.0s)\n", this->ipAddress.GetAscii()); + timeOffset=0.0; } + } - if (NtriggerCount == - numTrigger) // stop store when all trigger will be received - { - printf("ACQUIRED ALL FRAME BURST: %d\n", numTrigger); - storeEnabled = 0; - // break; - } - } // if (frameTriggerCounter == burstNframe) - } - else //( triggerMode == 1 ) //Internal trigger source - { - // Multiple trigger acquisition: first trigger save 64bit timestamp - timebaseNid = -1; // used in cammdsutils to use internal - triggered = 1; // debug - - if (startStoreTrg == 1) - { - gettimeofday(&tv, NULL); - timeStamp = - ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // timeStamp [ms] - if (timeStamp0 == 0) - { - Int64 *tsMDS = new Int64(timeStamp); - t0Node->putData(tsMDS); - timeStamp0 = timeStamp; - } - else - { - frameTime = (float)((timeStamp - timeStamp0) / - 1000.0); // interval from first frame [s] - // printf("frameTime: %f", frameTime); - } - } // if startStoreTrg == 1 + + frameBuffer = (short *) calloc(1, width * height * sizeof(short)); + frame8bit = (unsigned char *) calloc(1, width * height * sizeof(char)); - if (frameTriggerCounter == burstNframe) - { - startStoreTrg = 0; // disable storing - frameTriggerCounter = 0; - NtriggerCount++; - printf("Stop Internal trigger acquisition %f %f %f\n", frameTime, - burstDuration, frameRate); - // storeEnabled=0; //infinite trigger until stop acquisition - // break; - } - } // else Internal trigger source - } // if(storeEnabled) - - if (irFrameFormat != radiometric) - frameConv((unsigned short *)frameBuffer, width, - height); // convert kelvin in Celsius - - // frameStatus -> status=1 complete # status=2 incomplete # status=3 timeout - // # status=4 triggered frame + complete - if ((frameStatus != 3) && (storeEnabled == 1 && startStoreTrg == 1) && - (acqSkipFrameNumber <= 0 || - (frameTriggerCounter % (acqSkipFrameNumber + 1)) == 0)) - { - int frameTimeBaseIdx; - frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; - // printf("SAVE Frame : %d timebase Idx : %d\n", frameTriggerCounter, - // frameTimeBaseIdx); - - // CT la routine camSaveFrame utilizza il frame index in acquisizione. - // L'indice viene utilizzato per individuare nell'array della base - // temporale il tempo associato al frame. - - // Con Trigger interno viene utilizzato frameTime come tempo relativo allo - // 0; timebaseNid deve essere -1 - - camSaveFrame((void *)frameBuffer, width, height, frameTime, 14, - (void *)treePtr, framesNid, timebaseNid, frameTimeBaseIdx, - (void *)metaData, metaSize, framesMetadNid, saveList); - savedFrameNumber++; - } + metaSize = width * 3 * sizeof(short); + metaData = (short *)calloc(1, metaSize); - if (streamingEnabled) - { - if (tcpStreamHandle == -1) - { - rstatus = camOpenTcpConnection(streamingServer, streamingPort, - &tcpStreamHandle, width, height, - CSU_PIX_FMT_GRAY16); - if (rstatus != -1) - { - printf("Connected to FFMPEG on %s : %d\n", streamingServer, - streamingPort); - } - else + camStartSave(&saveList); // # Initialize save frame Linked list reference + + camStartStreaming(&streamingList); // # Initialize streaming frame Linked list reference + + burstNframe = (int) ( burstDuration * frameRate + 1 ); + + acqFlag = 1; + frameTriggerCounter = 0; + frameCounter = 0; + incompleteFrame = 0; + savedFrameNumber = 0; + + startStoreTrg = 0; //manage the mdsplus saving process. SAVE always start with a SW or HW trigger. (0=no-save; 1=save) + + while ( acqFlag ) + { + getFrame( &frameStatus, frameBuffer, metaData); //get the frame + + if(storeEnabled) { - printf("Cannot connect to FFMPEG on %s : %d. Disable streaming\n", - streamingServer, streamingPort); - streamingEnabled = 0; - } - } - // if ( (streamingSkipFrameNumber - 1 <= 0) || (frameCounter % ( - // streamingSkipFrameNumber - 1)) == 0 ) //20170327 - ORIGINAL - else if ((this->frameRate < 10) || - (frameCounter % int(this->frameRate / 10.0)) == - 0) // send frame @ 10Hz. Reduce CPU usage when radiometric - // conversion must be performed. - { - if (irFrameFormat == radiometric) + if ( triggerMode == 1 ) // External trigger source + { + + if ( ((frameStatus == 4) || eventTrigger == 1) && (startStoreTrg == 0) ) //start data storing @ 1st trigger seen (trigger is on image header!) + { //CT In External Trigger Mode acquisitio is also triggered on MDSevent + startStoreTrg = 1; + eventTrigger = 0; //CT Reset MDSplus trigger event flag + printf("TRIGGERED:\n"); + } + + if (frameTriggerCounter == burstNframe) + { + triggered = 0; + startStoreTrg = 0; //disable storing + NtriggerCount++; + + printf("ACQUIRED ALL FRAMES %d FOR TRIGGER : %d\n", int( frameTriggerCounter / (acqSkipFrameNumber + 1) ), NtriggerCount ); + frameTriggerCounter = 0; + + if ( autoCalibration ) //execute calibration action @ every burst of frames (only if NO auto calibration) + { + executeAutoCalib(); + } + + if ( NtriggerCount == numTrigger ) //stop store when all trigger will be received + { + printf("ACQUIRED ALL FRAME BURST: %d\n", numTrigger ); + storeEnabled=0; + //break; + } + }//if (frameTriggerCounter == burstNframe) + + } + else //( triggerMode == 1 ) //Internal trigger source + { + //Multiple trigger acquisition: first trigger save 64bit timestamp + timebaseNid = -1; //used in cammdsutils to use internal + triggered = 1; //debug + + if(startStoreTrg == 1) + { + gettimeofday(&tv, NULL); + timeStamp = ((tv.tv_sec)*1000) + ((tv.tv_usec)/1000); // timeStamp [ms] + + if(timeStamp0==0) + { + Int64 *tsMDS = new Int64(timeStamp); + t0Node->putData(tsMDS); + timeStamp0=timeStamp; + } + else + { + frameTime = (float)((timeStamp-timeStamp0)/1000.0); //interval from first frame [s] + //printf("frameTime: %f", frameTime); + } + }//if startStoreTrg == 1 + + if ( frameTriggerCounter == burstNframe ) + { + startStoreTrg = 0; //disable storing + frameTriggerCounter = 0; + NtriggerCount++; + printf("Stop Internal trigger acquisition %f %f %f\n", frameTime, burstDuration, frameRate); + //storeEnabled=0; //infinite trigger until stop acquisition + //break; + } + }//else Internal trigger source + }//if(storeEnabled) + + if ( irFrameFormat != radiometric ) + frameConv((unsigned short *)frameBuffer, width, height); //convert kelvin in Celsius + + //frameStatus -> status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete + if( (frameStatus != 3 ) && ( storeEnabled == 1 && startStoreTrg == 1 ) && ( acqSkipFrameNumber <= 0 || (frameTriggerCounter % (acqSkipFrameNumber + 1) ) == 0 ) ) + { + int frameTimeBaseIdx; + frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; + //printf("SAVE Frame : %d timebase Idx : %d\n", frameTriggerCounter, frameTimeBaseIdx); + + // CT la routine camSaveFrame utilizza il frame index in acquisizione. L'indice viene + // utilizzato per individuare nell'array della base temporale il tempo associato al frame. + + // Con Trigger interno viene utilizzato frameTime come tempo relativo allo 0; timebaseNid deve essere -1 + + camSaveFrame((void *)frameBuffer, width, height, frameTime+timeOffset, 14, (void *)treePtr, framesNid, timebaseNid, frameTimeBaseIdx, (void *)metaData, metaSize, framesMetadNid, saveList); + savedFrameNumber++; + } + + if( streamingEnabled ) + { + if( tcpStreamHandle == -1) + { + rstatus = camOpenTcpConnection(streamingServer, streamingPort, &tcpStreamHandle, width, height, CSU_PIX_FMT_GRAY16); + if( rstatus !=-1 ) + { + printf( "Connected to FFMPEG on %s : %d\n", streamingServer, streamingPort); + } + else + { + printf( "Cannot connect to FFMPEG on %s : %d. Disable streaming\n", streamingServer, streamingPort); + streamingEnabled = 0; + } + } + //if ( (streamingSkipFrameNumber - 1 <= 0) || (frameCounter % ( streamingSkipFrameNumber - 1)) == 0 ) //20170327 - ORIGINAL + else if((this->frameRate<10) || (frameCounter % int(this->frameRate/10.0))==0) //send frame @ 10Hz. Reduce CPU usage when radiometric conversion must be performed. + { + if( irFrameFormat == radiometric ) + { + flirRadiometricConv(frameBuffer, width, height, metaData); //radiometric conversion in Celsius using metadata + } + camStreamingFrame( tcpStreamHandle, frameBuffer, width, height, CSU_PIX_FMT_GRAY16, irFrameFormat, autoAdjustLimit, &lowLim, &highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, this->deviceName, streamingList); + } + } // if( streamingEnabled ) + + frameCounter++; //never resetted, used for frame timestamp + if ( startStoreTrg == 1 ) //CT incremento l'indice dei frame salvato solo se l'acquisizione e' stata triggerata { - flirRadiometricConv( - frameBuffer, width, height, - metaData); // radiometric conversion in Celsius using metadata + frameTriggerCounter++; } - camStreamingFrame(tcpStreamHandle, frameBuffer, width, height, - CSU_PIX_FMT_GRAY16, irFrameFormat, autoAdjustLimit, - &lowLim, &highLim, minLim, maxLim, adjRoiX, adjRoiY, - adjRoiW, adjRoiH, this->deviceName, streamingList); - } - } // if( streamingEnabled ) - - frameCounter++; // never resetted, used for frame timestamp - if (startStoreTrg == 1) // CT incremento l'indice dei frame salvato solo se - // l'acquisizione e' stata triggerata - { - frameTriggerCounter++; - } - } // endwhile + }//endwhile - camStopSave(saveList); // Stop asynhronous store stream - camStopStreaming(streamingList); // Stop asynhronous frame streaming + camStopSave(saveList); // Stop asynhronous store stream + camStopStreaming(streamingList); // Stop asynhronous frame streaming - if (tcpStreamHandle != -1) - camCloseTcpConnection(&tcpStreamHandle); + if( tcpStreamHandle != -1 ) + camCloseTcpConnection(&tcpStreamHandle); - rstatus = stopAcquisition(); // stop camera acquisition - if (rstatus < 0) - printf("Cannot stop camera acquisition\n"); + rstatus = stopAcquisition(); //stop camera acquisition + if (rstatus < 0) + printf("Cannot stop camera acquisition\n"); - if (!autoCalibration) - setCalibMode(1); // re-enable auto calibration + if ( !autoCalibration ) + setCalibMode(1); //re-enable auto calibration - free(frameBuffer); - free(frame8bit); - free(metaData); + + free(frameBuffer); + free(frame8bit); + free(metaData); - printf("Acquisition Statistics : \tTotal frames read %d, \n\t\t\t\tTotal " - "frames stored %d (expected %d), \n\t\t\t\tNumber of trigger %d " - "(expected %d), \n\t\t\t\tIncomplete frame %d\n", - frameCounter, savedFrameNumber, - numTrigger * - (1 + (int)(burstDuration * (frameRate - acqSkipFrameNumber))), - NtriggerCount, numTrigger, incompleteFrame); + printf("Acquisition Statistics : \tTotal frames read %d, \n\t\t\t\tTotal frames stored %d (expected %d), \n\t\t\t\tNumber of trigger %d (expected %d), \n\t\t\t\tIncomplete frame %d\n", frameCounter, savedFrameNumber, numTrigger * (1+(int)( burstDuration * (frameRate-acqSkipFrameNumber))), NtriggerCount, numTrigger, incompleteFrame ); - acqStopped = 1; + acqStopped = 1; - return rstatus; + return rstatus; } + diff --git a/device_support/flir/FLIRSC65X.h b/device_support/flir/FLIRSC65X.h index f38c2964ee..9f03f6d955 100644 --- a/device_support/flir/FLIRSC65X.h +++ b/device_support/flir/FLIRSC65X.h @@ -1,202 +1,221 @@ +#include +#include + #include -#include //new 9mar2016 for SDK4 +#include //new 9mar2016 for SDK4 #include -#include //new 9mar2016 for SDK4 +#include //new 9mar2016 for SDK4 + +enum FPS_ENUM { fps_200, fps_100, fps_50, fps_25, fps_12, fps_6, fps_3 }; +enum IRFMT_ENUM { radiometric, linear10mK, linear100mK }; +enum EXPMODE_ENUM { internal_mode, external_mode }; + +using namespace MDSplus; + +#ifdef __cplusplus +extern "C" +{ +#endif + +extern int flirRadiometricConv(void *frame, int width, int height, void *metaData); + +// Wrapper for Python that must see the cpp class as standard C functions + +int flirOpen(const char *cameraName, int *camHandle); +int flirClose(int camHandle); +int checkLastOp(int camHandle); +int printAllParameters(int camHandle); +int setExposureMode(int camHandle, EXPMODE_ENUM exposureMode); + +int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip); +int setFrameRateNew(int camHandle, double frameRate); + +int setIrFormat(int camHandle, IRFMT_ENUM irFormat); +int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height); +int setReadoutArea(int camHandle, int x, int y, int width, int height); +int setObjectParameters(int camHandle, double reflectedTemperature, double atmosphericTemperature, + double objectDistance, double objectEmissivity, + double relativeHumidity, double extOpticsTemperature, + double extOpticsTransmission, double estimatedTransmission); +int setMeasurementRange(int camHandle, int measRange); +int getFocusAbsPosition(int camHandle, int *focusPos); +int setFocusAbsPosition(int camHandle, int focusPos); +int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber ); + +int executeAutoFocus(int camHandle); +int setCalibMode(int camHandle, int calMode); +int executeAutoCalib(int camHandle); +int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); +int stopAcquisition(int camHandle); +int getFrame(int camHandle, int *status, void *frame, void *metaData); +int frameConv(int camHandle, unsigned short *frame, int width, int height); +int startFramesAcquisition(int camHandle); +int stopFramesAcquisition(int camHandle); + + +int setStreamingMode(int camHandle, IRFMT_ENUM irFormat, int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); + +int setTriggerMode(int camHandle, int triggerMode, double burstDuration, int numTrigger ); +int softwareTrigger(int camHandle); +int setTreeInfo( int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); + +void getLastError(int camHandle, char *msg); + +#ifdef __cplusplus +} +#endif -enum FPS_ENUM -{ - fps_200, - fps_100, - fps_50, - fps_25, - fps_12, - fps_6, - fps_3 -}; -enum IRFMT_ENUM -{ - radiometric, - linear10mK, - linear100mK -}; -enum EXPMODE_ENUM -{ - internal_mode, - external_mode -}; -#ifdef __cplusplus -extern "C" -{ -#endif - - extern int flirRadiometricConv(void *frame, int width, int height, - void *metaData); - - // Wrapper for Python that must see the cpp class as standard C functions - - int flirOpen(const char *cameraName, int *camHandle); - int flirClose(int camHandle); - int checkLastOp(int camHandle); - int printAllParameters(int camHandle); - int setExposureMode(int camHandle, EXPMODE_ENUM exposureMode); - - int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip); - int setFrameRateNew(int camHandle, double frameRate); - - int setIrFormat(int camHandle, IRFMT_ENUM irFormat); - int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height); - int setReadoutArea(int camHandle, int x, int y, int width, int height); - int setObjectParameters(int camHandle, double reflectedTemperature, - double atmosphericTemperature, double objectDistance, - double objectEmissivity, double relativeHumidity, - double extOpticsTemperature, - double extOpticsTransmission, - double estimatedTransmission); - int setMeasurementRange(int camHandle, int measRange); - int getFocusAbsPosition(int camHandle, int *focusPos); - int setFocusAbsPosition(int camHandle, int focusPos); - int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber); - - int executeAutoFocus(int camHandle); - int setCalibMode(int camHandle, int calMode); - int executeAutoCalib(int camHandle); - int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); - int stopAcquisition(int camHandle); - int getFrame(int camHandle, int *status, void *frame, void *metaData); - int frameConv(int camHandle, unsigned short *frame, int width, int height); - int startFramesAcquisition(int camHandle); - int stopFramesAcquisition(int camHandle); - - int setStreamingMode(int camHandle, IRFMT_ENUM irFormat, int streamingEnabled, - bool autoAdjustLimit, const char *streamingServer, - int streamingPort, int lowLim, int highLim, int adjRoiX, - int adjRoiY, int adjRoiW, int adjRoiH, - const char *deviceName); - - int setTriggerMode(int camHandle, int triggerMode, double burstDuration, - int numTrigger); - int softwareTrigger(int camHandle); - int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid); - - void getLastError(int camHandle, char *msg); - -#ifdef __cplusplus -} -#endif class FLIR_SC65X { -private: - PvDevice *lDevice; // camera handle - PvStream *lStream; // stream handle - PvBuffer *lBuffers; // buffer handle - PvResult lResult; // result of the latest operation - PvString ipAddress; // camera ip address - - int x; - int y; - int width; - int height; - int pixelFormat; // all pixelFormat supported are in camstreamutils.h - double frameRate; - - int storeEnabled; - int triggerMode; - int startStoreTrg; - int autoCalibration; - int irFrameFormat; - - int streamingEnabled; - int streamingSkipFrameNumber; - char streamingServer[512]; - int streamingPort; - int autoScale; - unsigned int lowLim; - unsigned int highLim; - unsigned int minLim; - unsigned int maxLim; - bool autoAdjustLimit; - int adjRoiX; - int adjRoiY; - int adjRoiW; - int adjRoiH; - char deviceName[64]; - - int imageMode; - int acqSkipFrameNumber; - double burstDuration; - int numTrigger; - - void *treePtr; - int framesNid; - int timebaseNid; - int framesMetadNid; - int frame0TimeNid; - - int acqFlag; - int acqStopped; - char error[512]; - int incompleteFrame; - - // debug - uint64_t currTime, lastTime, currIdx, lastIdx, triggered; - int64_t tickFreq; - -public: - // camera - FLIR_SC65X(const char *ipAddress); - FLIR_SC65X(); // new 23 July 2013 for test purposes - ~FLIR_SC65X(); - - // info - int checkLastOp(); - int printAllParameters(); - - // settings - int setExposureMode(EXPMODE_ENUM exposureMode); - int setFrameRate(double frameRate); - int setFrameRate(FPS_ENUM fps, int *frameToSkip); - int setIrFormat(IRFMT_ENUM irFormat); - int getReadoutArea(int *x, int *y, int *width, int *height); - int setReadoutArea(int x, int y, int width, int height); - int setObjectParameters(double reflectedTemperature, - double atmosphericTemperature, double objectDistance, - double objectEmissivity, double relativeHumidity, - double extOpticsTemperature, - double extOpticsTransmission, - double estimatedTransmission); - int setMeasurementRange(int measRange); - int getFocusAbsPosition(int *focusPos); - int setFocusAbsPosition(int focusPos); - int setCalibMode(int calibMode); - - int setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber); - int setStreamingMode(IRFMT_ENUM irFormat, int streamingEnabled, - bool autoAdjustLimit, const char *streamingServer, - int streamingPort, unsigned int lowLim, - unsigned int highLim, int adjRoiX, int adjRoiY, - int adjRoiW, int adjRoiH, const char *deviceName); - - int setTriggerMode(int triggerMode, double burstDuration, int numTrigger); - int setTreeInfo(void *treePtr, int frameNid, int timebaseNid, - int framesMetadNid, int frame0TimeNid); - - int executeAutoFocus(); - int executeAutoCalib(); - - void getLastError(char *msg); - void printLastError(const char *format, const char *msg); - - // acquisition - int startAcquisition(int *width, int *height, int *payloadSize); - int stopAcquisition(); - int softwareTrigger(); - int getFrame(int *status, void *frame, void *metaData); - int frameConv(unsigned short *frame, int width, int height); - int startFramesAcquisition(); - int stopFramesAcquisition(); - -protected: + + + class TriggerMdsEvent:public Event + { + private: + FLIR_SC65X* flir_sc65x; + public: + TriggerMdsEvent(const char *name, FLIR_SC65X* flir):Event(name) + { + flir_sc65x = flir; + } + + void run() + { + size_t bufSize; + const char *name = getName(); //Get the name of the event + char *date = getTime()->getDate(); //Get the event reception date in string format + const char *buf = getRaw(&bufSize); //Get raw data + char *str = new char[bufSize+1]; //Make it a string + memcpy(str, buf, bufSize); + str[bufSize] = 0; + //MDSevent trigger is set if camera is in acquisition, Frame store is enabled and camera is not saving frame. + //An event trigger received during acquisition can reset the trigger count to extend the acquisition + if(flir_sc65x->acqFlag && flir_sc65x->storeEnabled && flir_sc65x->startStoreTrg == 0) + { + printf("%s EVENT Trigger Start!!!!\n", flir_sc65x->ipAddress.GetAscii()); + flir_sc65x->eventTrigger = 1; + } else { + printf("%s EVENT Trigger Reset!!!!\n", flir_sc65x->ipAddress.GetAscii()); + flir_sc65x->eventTrigger = 0; + } + printf("%s RECEIVED EVENT %s AT %s WITH DATA %s Event Trig %d (%d,%d,%d)\n", flir_sc65x->ipAddress.GetAscii(), name, date, str, flir_sc65x->eventTrigger); + } + }; + + + + + private: + PvDevice *lDevice; //camera handle + PvStream *lStream; //stream handle + PvBuffer *lBuffers; //buffer handle + PvResult lResult; //result of the latest operation + PvString ipAddress; //camera ip address + + TriggerMdsEvent *trigEvent = nullptr; + + int x; + int y; + int width; + int height; + int pixelFormat; //all pixelFormat supported are in camstreamutils.h + double frameRate; + + int storeEnabled; + int triggerMode; + int startStoreTrg; + int autoCalibration; + int irFrameFormat; + int eventTrigger; //CT MDSplus event trigger flag + + int streamingEnabled; + int streamingSkipFrameNumber; + char streamingServer[512]; + int streamingPort; + int autoScale; + unsigned int lowLim; + unsigned int highLim; + unsigned int minLim; + unsigned int maxLim; + bool autoAdjustLimit; + int adjRoiX; + int adjRoiY; + int adjRoiW; + int adjRoiH; + char deviceName[64]; + + int imageMode; + int acqSkipFrameNumber; + double burstDuration; + int numTrigger; + + void* treePtr; + int framesNid; + int timebaseNid; + int framesMetadNid; + int frame0TimeNid; + + int acqFlag; + int acqStopped; + char error[512]; + int incompleteFrame; + + //debug + uint64_t currTime, lastTime, currIdx, lastIdx, triggered; + int64_t tickFreq; + + + public: + //camera + FLIR_SC65X(const char *ipAddress); + FLIR_SC65X(); //new 23 July 2013 for test purposes + ~FLIR_SC65X(); + + //info + int checkLastOp(); + int printAllParameters(); + + //settings + int setExposureMode(EXPMODE_ENUM exposureMode); + int setFrameRate(double frameRate); + int setFrameRate(FPS_ENUM fps, int *frameToSkip); + int setIrFormat(IRFMT_ENUM irFormat); + int getReadoutArea(int *x, int *y, int *width, int *height); + int setReadoutArea(int x, int y, int width, int height); + int setObjectParameters(double reflectedTemperature, double atmosphericTemperature, + double objectDistance, double objectEmissivity, + double relativeHumidity, double extOpticsTemperature, + double extOpticsTransmission, double estimatedTransmission); + int setMeasurementRange(int measRange); + int getFocusAbsPosition(int *focusPos); + int setFocusAbsPosition(int focusPos); + int setCalibMode(int calibMode); + + int setAcquisitionMode( int storeEnabled, int acqSkipFrameNumber ); + int setStreamingMode( IRFMT_ENUM irFormat, int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); + + int setTriggerMode( int triggerMode, double burstDuration, int numTrigger ); + int setTreeInfo( void *treePtr, int frameNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); + + + int executeAutoFocus(); + int executeAutoCalib(); + + void getLastError(char *msg); + void printLastError(const char *format, const char *msg); + + //acquisition + int startAcquisition(int *width, int *height, int *payloadSize); + int stopAcquisition(); + int softwareTrigger(); + int getFrame(int *status, void *frame, void *metaData); + int frameConv(unsigned short *frame, int width, int height); + int startFramesAcquisition(); + int stopFramesAcquisition(); + + + protected: + }; diff --git a/device_support/flir/flirutils.h b/device_support/flir/flirutils.h index dc550cf491..ac0f737d38 100644 --- a/device_support/flir/flirutils.h +++ b/device_support/flir/flirutils.h @@ -2,20 +2,15 @@ Radiometric Conversion functions for FLIR Camera */ -#ifdef __cplusplus -extern "C" -{ -#endif - int flirRadiometricConv(void *frame, int width, int height, void *metaData); - int flirRadiometricConvPar(void *frame, int width, int height, void *metaData, - float atmTemp, float emissivity, - float objectDistance, float ambTemp, float relHum); - void flirRadiometricConvFrames(void *frame, int width, int height, - int numFrames, void *metaData); - void flirRadiometricConvFramesPar(void *frame, int width, int height, - int numFrames, void *metaData, float *atmTemp, - float *emissivity, float *objectDistance, - float *ambTemp, float *relHum); -#ifdef __cplusplus -} -#endif +#ifdef __cplusplus +extern "C" +{ +#endif +int flirRadiometricConv(void *frame, int width, int height, void *metaData); +int flirRadiometricConvPar(void *frame, int width, int height, void *metaData, float atmTemp, float emissivity, float objectDistance, float ambTemp, float relHum); +void flirRadiometricConvFrames(void *frame, int width, int height, int numFrames, void *metaData); +void flirRadiometricConvFramesPar(void *frame, int width, int height, int numFrames, void *metaData, float *atmTemp, float *emissivity, float *objectDistance, float *ambTemp, float *relHum); +void flirRadiometricParGet(void *metaData, float *R, float *B, float *F); +#ifdef __cplusplus +} +#endif diff --git a/device_support/flir/main.cpp b/device_support/flir/main.cpp index afcf11c73f..1c7330b175 100644 --- a/device_support/flir/main.cpp +++ b/device_support/flir/main.cpp @@ -31,32 +31,32 @@ using namespace MDSplus; #include #include -#include "flirutils.h" //flir radiometric conversion +#include "flirutils.h" //flir radiometric conversion #include "fff.h" -#define USETHECAMERA // this let to use the camera or if not defined to read data from a pulse file. -int main(int argc, char **argv) +#define USETHECAMERA //this let to use the camera or if not defined to read data from a pulse file. + + +int main(int argc, char **argv ) { - if ((argv[1] == NULL) || (argv[2] == NULL) || - (argv[3] == NULL)) // argv[4] is OPTIONAL - { - printf("Please insert: 1)tree name 2)shot number 3)number of frame to " - "acquire 4) Streaming Port (OPTIONAL)\n"); - exit(0); + if((argv[1]==NULL) || (argv[2]==NULL) || (argv[3]==NULL)) // argv[4] is OPTIONAL + { + printf("Please insert: 1)tree name 2)shot number 3)number of frame to acquire 4) Streaming Port (OPTIONAL)\n"); + exit(0); } - // MDSPLUS +//MDSPLUS int res; void *treePtr; - res = camOpenTree(argv[1], atoi(argv[2]), &treePtr); - if (res == -1) + res=camOpenTree(argv[1], atoi( argv[2] ), &treePtr); + if(res==-1) { - printf("Error opening tree...\n"); - exit(0); + printf("Error opening tree...\n"); + exit(0); } - Tree *tree; + Tree *tree; TreeNode *node; TreeNode *nodeMeta; int dataNid; @@ -64,229 +64,210 @@ int main(int argc, char **argv) try { tree = (Tree *)treePtr; - node = tree->getNode((char *)"\\CAMERATEST::TOP:POINTGRAY:FRAMES"); - nodeMeta = - tree->getNode((char *)"\\CAMERATEST::TOP:POINTGRAY:FRAMES_METAD"); - dataNid = node->getNid(); // Node id to save the acquired frames - } - catch (const MdsException &exc) - { - std::cout << "ERROR reading data" << exc.what() << "\n"; - } + node=tree->getNode((char *)"\\CAMERATEST::TOP:POINTGRAY:FRAMES"); + nodeMeta=tree->getNode((char *)"\\CAMERATEST::TOP:POINTGRAY:FRAMES_METAD"); + dataNid=node->getNid(); //Node id to save the acquired frames + }catch ( MdsException *exc ) + { std::cout << "ERROR reading data" << exc->what() << "\n"; } printf("frame node path: %s\n", node->getPath()); - // MDSPLUS END +//MDSPLUS END + + #ifndef USETHECAMERA - /*read frame and metadata from stored pulse file and use Radiometric - * Conversion*/ +/*read frame and metadata from stored pulse file and use Radiometric Conversion*/ - Array *frameArray; - Array *frameArrayMeta; - int *shape; - int *shapeMeta; - int nEle = 3; + Array *frameArray; + Array *frameArrayMeta; + int *shape; + int *shapeMeta; + int nEle = 3; - Data *frameData; - Data *frameDataMeta; - short *framePtr; - char *framePtrMeta; + Data *frameData; + Data *frameDataMeta; + short *framePtr; + char *framePtrMeta; - try - { - frameArray = node->getSegment(0); // idx - frameArrayMeta = nodeMeta->getSegment(0); // idx + try + { + frameArray = node->getSegment(0); //idx + frameArrayMeta = nodeMeta->getSegment(0); //idx - shape = - (frameArray)->getShape(&nEle); // shape[0]=numframe=1 shape[1]=numbyte - shapeMeta = (frameArrayMeta) - ->getShape(&nEle); // shape[0]=numframe=1 shape[1]=numbyte + shape = (frameArray)->getShape(&nEle); //shape[0]=numframe=1 shape[1]=numbyte + shapeMeta = (frameArrayMeta)->getShape(&nEle); //shape[0]=numframe=1 shape[1]=numbyte - int numbytes = shape[1]; - int numframes = shape[0]; + int numbytes = shape[1]; + int numframes = shape[0]; - frameData = (frameArray)->getElementAt(0); - frameDataMeta = (frameArrayMeta)->getElementAt(0); + frameData = (frameArray)->getElementAt(0); + frameDataMeta = (frameArrayMeta)->getElementAt(0); - int dataDims[3]; - int dataDimsMeta[3]; - framePtr = (frameData)->getShortArray(dataDims); - framePtrMeta = (frameDataMeta)->getByteArray(dataDimsMeta); - } - catch (const MdsException &exc) - { - std::cout << "ERROR reading data" << exc.what() << "\n"; - } + int dataDims[3]; + int dataDimsMeta[3]; + framePtr = (frameData)->getShortArray(dataDims); + framePtrMeta = (frameDataMeta)->getByteArray(dataDimsMeta); + } + catch ( MdsException *exc ) + { std::cout << "ERROR reading data" << exc->what() << "\n"; } - FLIR_SC65X *FlirCam; - FlirCam = new FLIR_SC65X(); // open without ip adress because we not use a - // phisical camera! - printf("Radiometric Conversion Started\n"); - flirRadiometricConv(framePtr, 640, 480, framePtrMeta); - // flirRadiometricConvPar(framePtr, 640, 480, framePtrMeta, 293.15, 0.05, 0.5, - // 293.15, 60.0); - printf("Radiometric Conversion Ended\n"); + + FLIR_SC65X *FlirCam; + FlirCam = new FLIR_SC65X(); //open without ip adress because we not use a phisical camera! + printf("Radiometric Conversion Started\n"); + flirRadiometricConv(framePtr, 640, 480, framePtrMeta); + //flirRadiometricConvPar(framePtr, 640, 480, framePtrMeta, 293.15, 0.05, 0.5, 293.15, 60.0); + printf("Radiometric Conversion Ended\n"); #endif + #ifdef USETHECAMERA - // INIT STREAMING - int kSockHandle = -1; // MUST BE -1 THE FIRST TIME !!! - int i = 1; - int canStream = -1; +//INIT STREAMING + int kSockHandle=-1; //MUST BE -1 THE FIRST TIME !!! + int i=1; + int canStream=-1; - if (argv[4] != NULL) - { +if(argv[4]!=NULL) +{ - while (canStream == -1 && i <= 5) // try 5 times to open the connection - { - canStream = - camOpenTcpConnection((const char *)"127.0.0.1", atoi(argv[4]), - &kSockHandle, 640, 480, CSU_PIX_FMT_GRAY16); - sleep(1); - i++; - } - if (canStream == 0) - { - printf("Streaming OK!\n"); - } - else - { - printf("CANNOT Streaming!\n"); - } + while(canStream==-1 && i<=5) //try 5 times to open the connection + { + canStream=camOpenTcpConnection((const char *)"127.0.0.1", atoi(argv[4]), &kSockHandle, 640, 480, CSU_PIX_FMT_GRAY16); + sleep(1); + i++; } - // END STREAMING - - // FLIR - - FLIR_SC65X *FlirCam; - FlirCam = new FLIR_SC65X("192.168.100.18"); // vecchia 169.254.169.249 //nuova - // 169.254.76.254 //192.168.50.20 - if (!FlirCam->checkLastOp()) - { - printf("Unable to connect!!!\n"); - exit(0); + if(canStream==0) + { + printf("Streaming OK!\n"); } else - { - printf("Successfully connected...\n"); + { + printf("CANNOT Streaming!\n"); } - int skipFrame = 0; - int width = 0; - int height = 0; - int payloadSize = 0; - int x, y = 0; - - // FlirCam->setObjectParameters(291.15, 292.15, 1.0, 0.95, 0.5, - //294.15, 1.0, 0.0); FlirCam->setExposureMode(external_mode); //internal_mode - //external_mode FlirCam->setFrameRate(fps_25, &skipFrame); //200 100 50 25 12 - //6 3 FlirCam->setIrFormat(radiometric); //radiometric - //linear10mK linear100mK FlirCam->setMeasurementRange(2); - // FlirCam->setReadoutArea(0, 0, 400, 200); //NOT TO USE. setFrameRate set - // also ReadoutArea! - // FlirCam->getReadoutArea(&x, &y, &width, &height); - // printf("Start x:%d Start y:%d Width:%d Height:%d\n", x, y, width, - //height); - - printf("\nGETTING ALL CAMERA PARAMETERS: start\n"); - FlirCam->printAllParameters(); - printf("\nGETTING ALL CAMERA PARAMETERS: end\n\n"); - - // printf("TEST OF FOCUS POSITION.\n"); - // int focusPos = 0; - // FlirCam->getFocusAbsPosition(&focusPos); - // printf("Current Focus position: %d\n", focusPos); - // focusPos=37; - // printf("Try to set focus position @: %d\n", focusPos); - // FlirCam->setFocusAbsPosition(focusPos); - // FlirCam->getFocusAbsPosition(&focusPos); - // printf("New Focus position: %d\n", focusPos); - - FlirCam->startAcquisition(&width, &height, &payloadSize); - // printf( "2019-09-17: CODE COMMENTED FOR POINT GRAY TESTS \n"); - - int status; - void *metaData; - void *frame; - void *frame8bit; - int frameNumber = 0; - struct timeval tv; - int64_t timeStamp; - - frame = malloc(width * height * sizeof(short)); - frame8bit = malloc(width * height * sizeof(char)); - metaData = malloc(payloadSize - (width * height * sizeof(short))); - - // printf("Executing auto calibration and auto focus...\n"); - // FlirCam->setCalibMode(0); - // FlirCam->executeAutoCalib(); - // FlirCam->executeAutoFocus(); - - for (int i = 1; i <= atoi(argv[3]); i++) // acquire i=argv[3] frames - { - frameNumber++; - FlirCam->getFrame(&status, frame, metaData); - gettimeofday(&tv, NULL); - timeStamp = ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // timeStamp [ms] - switch (status) +} +//END STREAMING + + +//FLIR + + FLIR_SC65X *FlirCam; + FlirCam = new FLIR_SC65X("192.168.100.18"); //vecchia 169.254.169.249 //nuova 169.254.76.254 //192.168.50.20 + if(!FlirCam->checkLastOp()) { - case 1: - printf("get frame %d complete @ %ld\n", frameNumber, timeStamp); - break; - case 2: - printf("get frame %d incomplete @ %ld\n", frameNumber, timeStamp); - break; - case 3: - printf("get frame %d timeout @ %ld\n", frameNumber, timeStamp); - break; - case 4: - printf("get frame %d complete+triggered @ %ld\n", frameNumber, timeStamp); - break; - } - - if (status == 1 or status == 4) + printf("Unable to connect!!!\n"); + exit(0); + } + else { - // SAVE FRAME IN MDSPLUS - - /* res=camSaveFrame(frame, width, height, &timeStamp, 14, - treePtr, dataNid, -1, frameNumber); if(res==-1) - { - printf("Error in 'camSaveFrame'...\n"); - } - else - { - printf("Frame saved...\n"); - } - */ - // STREAMING - if (skipFrame == 0) - printf("ERROR SKIPFRAME=0\n"); - int sendFrame = i % skipFrame; - if (canStream == 0 and sendFrame == 0) - { - // streaming is set to 640 x 480 in "camOpenTcpConnection". - // It must be changed to prevent strange image transmission! - unsigned int lowLim = 0; - unsigned int highLim = 32000; - - camFrameTo8bit((unsigned short *)frame, 640, 480, CSU_PIX_FMT_GRAY16, - (unsigned char *)frame8bit, 1, &lowLim, &highLim, 2000, - 62000, 0, 0, 640, 480); - // printf("LowLim:%d HighLim:%d\n",lowLim, highLim); - camSendFrameOnTcp(&kSockHandle, width, height, frame8bit); + printf("Successfully connected...\n"); + } + + int skipFrame = 0; + int width=0; + int height=0; + int payloadSize=0; + int x,y=0; + +// FlirCam->setObjectParameters(291.15, 292.15, 1.0, 0.95, 0.5, 294.15, 1.0, 0.0); +// FlirCam->setExposureMode(external_mode); //internal_mode external_mode +// FlirCam->setFrameRate(fps_25, &skipFrame); //200 100 50 25 12 6 3 +// FlirCam->setIrFormat(radiometric); //radiometric linear10mK linear100mK +// FlirCam->setMeasurementRange(2); + //FlirCam->setReadoutArea(0, 0, 400, 200); //NOT TO USE. setFrameRate set also ReadoutArea! +// FlirCam->getReadoutArea(&x, &y, &width, &height); +// printf("Start x:%d Start y:%d Width:%d Height:%d\n", x, y, width, height); + + printf("\nGETTING ALL CAMERA PARAMETERS: start\n"); + FlirCam->printAllParameters(); + printf("\nGETTING ALL CAMERA PARAMETERS: end\n\n"); + +// printf("TEST OF FOCUS POSITION.\n"); +// int focusPos = 0; +// FlirCam->getFocusAbsPosition(&focusPos); +// printf("Current Focus position: %d\n", focusPos); +// focusPos=37; + // printf("Try to set focus position @: %d\n", focusPos); + // FlirCam->setFocusAbsPosition(focusPos); +// FlirCam->getFocusAbsPosition(&focusPos); +// printf("New Focus position: %d\n", focusPos); + + + FlirCam->startAcquisition(&width, &height, &payloadSize); +// printf( "2019-09-17: CODE COMMENTED FOR POINT GRAY TESTS \n"); + + int status; + void *metaData; + void *frame; + void *frame8bit; + int frameNumber = 0; + struct timeval tv; + int64_t timeStamp; + + frame=malloc(width*height*sizeof(short)); + frame8bit=malloc(width*height*sizeof(char)); + metaData=malloc(payloadSize-(width*height*sizeof(short))); + +// printf("Executing auto calibration and auto focus...\n"); +// FlirCam->setCalibMode(0); +// FlirCam->executeAutoCalib(); + // FlirCam->executeAutoFocus(); + + for(int i=1; i<=atoi(argv[3]); i++) //acquire i=argv[3] frames + { + frameNumber++; + FlirCam->getFrame(&status, frame, metaData); + gettimeofday(&tv, NULL); + timeStamp = ((tv.tv_sec)*1000) + ((tv.tv_usec)/1000); // timeStamp [ms] + switch(status) + { + case 1: printf("get frame %d complete @ %ld\n", frameNumber, timeStamp); break; + case 2: printf("get frame %d incomplete @ %ld\n", frameNumber, timeStamp); break; + case 3: printf("get frame %d timeout @ %ld\n", frameNumber, timeStamp); break; + case 4: printf("get frame %d complete+triggered @ %ld\n", frameNumber, timeStamp); break; } - } - } // for - - if (kSockHandle != -1) - camCloseTcpConnection(&kSockHandle); // close streaming - - FlirCam->setCalibMode(1); // auto calib - FlirCam->stopAcquisition(); - delete FlirCam; + if(status==1 or status==4) + { + //SAVE FRAME IN MDSPLUS + +/* res=camSaveFrame(frame, width, height, &timeStamp, 14, treePtr, dataNid, -1, frameNumber); + if(res==-1) + { + printf("Error in 'camSaveFrame'...\n"); + } + else + { + printf("Frame saved...\n"); + } +*/ + //STREAMING + if(skipFrame==0) printf("ERROR SKIPFRAME=0\n"); + int sendFrame = i % skipFrame; + if( canStream==0 and sendFrame==0 ) + { + //streaming is set to 640 x 480 in "camOpenTcpConnection". + //It must be changed to prevent strange image transmission! + unsigned int lowLim = 0; + unsigned int highLim = 32000; + + camFrameTo8bit((unsigned short *)frame, 640, 480, CSU_PIX_FMT_GRAY16, (unsigned char *)frame8bit, 1, &lowLim, &highLim, 2000, 62000, 0, 0, 640, 480); + // printf("LowLim:%d HighLim:%d\n",lowLim, highLim); + camSendFrameOnTcp(&kSockHandle, width, height, frame8bit); + } + + } + + }//for + + if(kSockHandle!=-1) camCloseTcpConnection(&kSockHandle); //close streaming + + FlirCam->setCalibMode(1); //auto calib + FlirCam->stopAcquisition(); + delete FlirCam; #endif + } diff --git a/device_support/national/Makefile b/device_support/national/Makefile index 4e0b8108a0..a9ed5b2c65 100644 --- a/device_support/national/Makefile +++ b/device_support/national/Makefile @@ -23,9 +23,9 @@ LDFLAGS = -fPIC -O0 -L${MDSPLUS_DIR}/lib -L${CODAC_ROOT}/lib/ -lm -lNiFpga -lpx SOURCES_LIB=NiInterface.cpp cRioFAUfunction.cpp cRioMPAGfunction.cpp AsyncStoreManager.cpp OBJECTS=$(SOURCES_LIB:.cpp=.o) SHAREDLIB=libNiInterface.so -EXE_PROGRAM=generateWave probeTermControl startStopTermControl writeDigitalOut print_device_info pxi6259devList.sh pxie6368devList.sh +EXE_PROGRAM=generateWave probeTermControl startStopTermControl writeDigitalOut testELADDigitalOut testELADDigitalIn print_device_info pxi6259devList.sh pxie6368devList.sh -SOURCES_EXE=generateWave.cpp probeTermControl.cpp startStopTermControl.cpp writeDigitalOut.cpp print_device_info.cpp +SOURCES_EXE=generateWave.cpp probeTermControl.cpp startStopTermControl.cpp writeDigitalOut.cpp print_device_info.cpp testELADDigitalOut.cpp testELADDigitalIn.cpp BIN = $(patsubst %.cpp,%,$(SOURCES_EXE)) diff --git a/device_support/national/testELADDigitalIn.cpp b/device_support/national/testELADDigitalIn.cpp new file mode 100644 index 0000000000..e76032b9d0 --- /dev/null +++ b/device_support/national/testELADDigitalIn.cpp @@ -0,0 +1,319 @@ +/* + * dioex1.c + * + * dioex1 demonstrates software-timed, static DIO operation using DIO ports 0, 1, and 2. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +int number_of_ports = 3; + +int test(char * device_name, int silent) +{ + + xseries_di_conf_t di_conf; + xseries_do_conf_t do_conf; + + + int retval = 0; + + int dio_fd = 0; + int pfi_fd = 0; + int trig_fd = 0; + + char str[100]; + + //uint32_t dio_output_mask = 0x1A2B3C4D;//1 1010 0010 1011 0011 1100 0100 1101 + //uint32_t dio_output_mask = 0xF0F0F; // 1111 0000 1111 0000 1111 + uint32_t dio_output_mask = 0; // all input + uint32_t dio_input_mask = (~dio_output_mask) & 0xFFFFFFFF; + + + + //uint16_t pfi_output_mask = 0x5E6F;//101 1110 0110 1111 + //uint16_t pfi_output_mask = 0xF; // 1111 + uint16_t pfi_output_mask = 0; // all input + uint16_t pfi_input_mask = (~pfi_output_mask) & 0xFFFF; + + uint32_t do_value = 0x98765ADF;//1001 1000 0111 0110 0101 1010 1101 1111 + uint32_t di_value = 0; + + uint32_t pfi_write_value = 0x4665;//100 0110 0110 0101 + uint32_t pfi_read_value = 0; + + /* open DIO segment file descriptor */ + sprintf(str,"%s.dio",device_name); + dio_fd = open(str, O_RDWR); + if (dio_fd <= 0) { + printf("Could not open AO segment!\n"); + retval = -1; + goto out; + } + + /* open PFI segment file descriptor */ + sprintf(str,"%s.pfi",device_name); + pfi_fd = open(str, O_RDWR); + if (pfi_fd <= 0) { + printf("Could not open AO segment!\n"); + retval = -1; + goto out; + } + + /* open TRIG segment file descriptor */ + sprintf(str,"%s.trig",device_name); + trig_fd = open(str, O_RDWR); + if (trig_fd <= 0) { + printf("Could not open AO segment!\n"); + retval = -1; + goto out; + } + + /* Stop the segment */ + xseries_stop_di(dio_fd); + xseries_stop_do(dio_fd); + + /* reset DIO segment */ + retval = xseries_reset_dio(dio_fd); + if (retval != 0) { + printf("Error reseting DIO segment!\n"); + goto out; + } + + /* free PFI lines */ + retval = xseries_free_pfi_lines(trig_fd,0xFFFF); + if (retval != 0) { + printf ("Err, cannot free all PFI lines: %s\n", strerror(errno)); + goto out; + } + + /* reset PFI segment */ + retval = xseries_reset_pfi(trig_fd); + if (retval != 0) { + printf("Error reseting PFI segment!\n"); + goto out; + } + + /* + * Configure DIO segment + */ + + /* Create AO configuration */ + di_conf = xseries_static_di(dio_input_mask); + do_conf = xseries_static_do(dio_output_mask); + + /* Configure PFI/TRIG segment */ + retval = xseries_set_pfi_for_input(trig_fd, pfi_input_mask); + if (retval != 0) { + printf("Error setting PFI input mask!\n"); + goto out; + } + retval = xseries_set_pfi_for_output(trig_fd, pfi_output_mask, XSERIES_PFI_OUTPUT_DO); + if (retval != 0) { + printf("Error setting PFI output mask!\n"); + goto out; + } + + /* Load DIO configuration */ + retval = xseries_load_di_conf(dio_fd, di_conf); + if (retval != 0) { + printf("Error loading DI configuration!\n"); + goto out; + } + retval = xseries_load_do_conf(dio_fd, do_conf); + if (retval != 0) { + printf("Error loading DO configuration!\n"); + goto out; + } + + /* start DIO*/ + retval = xseries_start_di(dio_fd); + if (retval != 0) { + printf("Error loading DI configuration!\n"); + goto out; + } + retval = xseries_start_do(dio_fd); + if (retval != 0) { + printf("Error loading DO configuration!\n"); + goto out; + } + + printf("Read on P0 PFI0 "); + scanf("%d", &do_value); + + while(1) + { + +/* + printf("Write on DIO P0 [ con0 : 0 to 3 con1 : 8 to 11 ] "); + scanf("%d", &do_value); + + do_value = 1 << do_value; + + // Write values to ports + retval = xseries_write_do(dio_fd,&do_value,1); + if (retval != 1) { + printf("Error writing DO value!\n"); + break; + } + + printf("Write on DIO [con 0 : PFI 0 to 3 con1 : PO 16 to 19 ] "); + scanf("%d", &pfi_write_value); + + if( pfi_write_value < 16) + { + + pfi_write_value = 1 << pfi_write_value; + retval = xseries_write_pfi(pfi_fd, &pfi_write_value, 1); + if (retval != 1) { + printf("Error writing PFI value!\n"); + break; + } + } else { + + do_value = do_value | 1 << pfi_write_value; + + // Write values to ports + retval = xseries_write_do(dio_fd,&do_value,1); + if (retval != 1) { + printf("Error writing DO value!\n"); + break; + } + } +*/ + /* Read written values */ + + retval = xseries_read_di(dio_fd,&di_value,1); + if (retval != 1) { + printf("Error reading DI value!\n"); + goto out; + } + //printf("Read P0 %d\n", di_value); + if( di_value != 0) + printf("%d-", di_value); + + retval = xseries_read_pfi(pfi_fd,&pfi_read_value,1); + if (retval != 1) { + printf("Error reading PFI value!\n"); + goto out; + } + //printf("Read PFI %d\n", pfi_read_value); + + sleep(0.1); + + + } + + + /* Read written values */ + /* + retval = xseries_read_di(dio_fd,&di_value,1); + if (retval != 1) { + printf("Error reading DI value!\n"); + goto out; + } + retval = xseries_read_pfi(pfi_fd,&pfi_read_value,1); + if (retval != 1) { + printf("Error reading PFI value!\n"); + goto out; + } + */ + /* Read PFI and DIO port value */ + /* + if((di_value & dio_output_mask) != (do_value & dio_output_mask)) { + printf("Read DIO value not correct!\n"); + retval = -1; + } + if((pfi_read_value & pfi_output_mask )!= (pfi_write_value & pfi_output_mask)) { + printf("Read PFI value not correct!\n"); + retval = -1; + } + */ + /* Read and write functions return number of samples so retval must be reset to 0 */ + retval = 0; + +out: + + /* stop the segment */ + xseries_stop_di(dio_fd); + xseries_stop_do(dio_fd); + + /* Free PFI lines */ + xseries_free_pfi_lines(trig_fd, 0XFFFF); + + /* reset segment */ + xseries_reset_dio(dio_fd); + xseries_reset_pfi(pfi_fd); + + /* close segment's file descriptor */ + close(dio_fd); + close(pfi_fd); + + return retval; +} + +void print_text(void){ + printf ("\n"); + + printf("Test software-timed, static DIO and PFI operation using DIO and PFI ports.\n"); + printf ("\n"); +} + +int main (int argc, char** argv) { + + int retval = 0; + char * device_name; + int silent = false; + + if (argc == 2) { + device_name = argv[1]; + print_text(); + } else if (argc == 3) { + device_name = argv[1]; + if(strcmp(argv[2],"-silent") != 0) { + print_text(); + silent = false; + } else { + silent = true; + } + } else { + printf ("Usage: %s \n", argv[0]); + printf ("Example:\n %s /dev/pxie-6368.0\n", argv[0]); + printf ("\n"); + exit(EXIT_FAILURE); + } + + if (silent) { + printf("%-10s%-100s", + argv[0], + "Test software-timed, static DIO and PFI operation using DIO and PFI ports."); + fflush(stdout); + } + + /* run test */ + retval = test(device_name,silent); + + if (!silent) { + printf("Test: "); + fflush(stdout); + } + + printf("[%s]\n",retval!=0? "FAILED":"OK"); + + if(!silent) { printf ("\n");} + + return retval; +} + diff --git a/device_support/national/testELADDigitalOut.cpp b/device_support/national/testELADDigitalOut.cpp new file mode 100644 index 0000000000..6a03f3cbfd --- /dev/null +++ b/device_support/national/testELADDigitalOut.cpp @@ -0,0 +1,308 @@ +/* + * dioex1.c + * + * dioex1 demonstrates software-timed, static DIO operation using DIO ports 0, 1, and 2. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +int number_of_ports = 3; + +int test(char * device_name, int silent) +{ + + xseries_di_conf_t di_conf; + xseries_do_conf_t do_conf; + + + int retval = 0; + + int dio_fd = 0; + int pfi_fd = 0; + int trig_fd = 0; + + char str[100]; + + //uint32_t dio_output_mask = 0x1A2B3C4D;//1 1010 0010 1011 0011 1100 0100 1101 + uint32_t dio_output_mask = 0xF0F0F; // 1111 0000 1111 0000 1111 + uint32_t dio_input_mask = (~dio_output_mask) & 0xFFFFFFFF; + + //uint16_t pfi_output_mask = 0x5E6F;//101 1110 0110 1111 + uint16_t pfi_output_mask = 0xF; // 1111 + + uint16_t pfi_input_mask = (~pfi_output_mask) & 0xFFFF; + + uint32_t do_value = 0x98765ADF;//1001 1000 0111 0110 0101 1010 1101 1111 + uint32_t di_value = 0; + + uint32_t pfi_write_value = 0x4665;//100 0110 0110 0101 + uint32_t pfi_read_value = 0; + + /* open DIO segment file descriptor */ + sprintf(str,"%s.dio",device_name); + dio_fd = open(str, O_RDWR); + if (dio_fd <= 0) { + printf("Could not open AO segment!\n"); + retval = -1; + goto out; + } + + /* open PFI segment file descriptor */ + sprintf(str,"%s.pfi",device_name); + pfi_fd = open(str, O_RDWR); + if (pfi_fd <= 0) { + printf("Could not open AO segment!\n"); + retval = -1; + goto out; + } + + /* open TRIG segment file descriptor */ + sprintf(str,"%s.trig",device_name); + trig_fd = open(str, O_RDWR); + if (trig_fd <= 0) { + printf("Could not open AO segment!\n"); + retval = -1; + goto out; + } + + /* Stop the segment */ + xseries_stop_di(dio_fd); + xseries_stop_do(dio_fd); + + /* reset DIO segment */ + retval = xseries_reset_dio(dio_fd); + if (retval != 0) { + printf("Error reseting DIO segment!\n"); + goto out; + } + + /* free PFI lines */ + retval = xseries_free_pfi_lines(trig_fd,0xFFFF); + if (retval != 0) { + printf ("Err, cannot free all PFI lines: %s\n", strerror(errno)); + goto out; + } + + /* reset PFI segment */ + retval = xseries_reset_pfi(trig_fd); + if (retval != 0) { + printf("Error reseting PFI segment!\n"); + goto out; + } + + /* + * Configure DIO segment + */ + + /* Create AO configuration */ + di_conf = xseries_static_di(dio_input_mask); + do_conf = xseries_static_do(dio_output_mask); + + /* Configure PFI/TRIG segment */ + retval = xseries_set_pfi_for_input(trig_fd, pfi_input_mask); + if (retval != 0) { + printf("Error setting PFI input mask!\n"); + goto out; + } + retval = xseries_set_pfi_for_output(trig_fd, pfi_output_mask, XSERIES_PFI_OUTPUT_DO); + if (retval != 0) { + printf("Error setting PFI output mask!\n"); + goto out; + } + + /* Load DIO configuration */ + retval = xseries_load_di_conf(dio_fd, di_conf); + if (retval != 0) { + printf("Error loading DI configuration!\n"); + goto out; + } + retval = xseries_load_do_conf(dio_fd, do_conf); + if (retval != 0) { + printf("Error loading DO configuration!\n"); + goto out; + } + + /* start DIO*/ + retval = xseries_start_di(dio_fd); + if (retval != 0) { + printf("Error loading DI configuration!\n"); + goto out; + } + retval = xseries_start_do(dio_fd); + if (retval != 0) { + printf("Error loading DO configuration!\n"); + goto out; + } + + while(1) + { + + printf("Write on DIO P0 [ con0 : 0 to 3 con1 : 8 to 11 ] "); + scanf("%d", &do_value); + + do_value = 1 << do_value; + + /* Write values to ports */ + retval = xseries_write_do(dio_fd,&do_value,1); + if (retval != 1) { + printf("Error writing DO value!\n"); + break; + } + + printf("Write on DIO [con 0 : PFI 0 to 3 con1 : PO 16 to 19 ] "); + scanf("%d", &pfi_write_value); + + if( pfi_write_value < 16) + { + + pfi_write_value = 1 << pfi_write_value; + retval = xseries_write_pfi(pfi_fd, &pfi_write_value, 1); + if (retval != 1) { + printf("Error writing PFI value!\n"); + break; + } + } else { + + do_value = do_value | 1 << pfi_write_value; + + /* Write values to ports */ + retval = xseries_write_do(dio_fd,&do_value,1); + if (retval != 1) { + printf("Error writing DO value!\n"); + break; + } + } + + /* Read written values */ + + retval = xseries_read_di(dio_fd,&di_value,1); + if (retval != 1) { + printf("Error reading DI value!\n"); + goto out; + } + printf("Read P0 %d\n", di_value); + + retval = xseries_read_pfi(pfi_fd,&pfi_read_value,1); + if (retval != 1) { + printf("Error reading PFI value!\n"); + goto out; + } + printf("Read PFI %d\n", pfi_read_value); + + + } + + + /* Read written values */ + /* + retval = xseries_read_di(dio_fd,&di_value,1); + if (retval != 1) { + printf("Error reading DI value!\n"); + goto out; + } + retval = xseries_read_pfi(pfi_fd,&pfi_read_value,1); + if (retval != 1) { + printf("Error reading PFI value!\n"); + goto out; + } + */ + /* Read PFI and DIO port value */ + /* + if((di_value & dio_output_mask) != (do_value & dio_output_mask)) { + printf("Read DIO value not correct!\n"); + retval = -1; + } + if((pfi_read_value & pfi_output_mask )!= (pfi_write_value & pfi_output_mask)) { + printf("Read PFI value not correct!\n"); + retval = -1; + } + */ + /* Read and write functions return number of samples so retval must be reset to 0 */ + retval = 0; + +out: + + /* stop the segment */ + xseries_stop_di(dio_fd); + xseries_stop_do(dio_fd); + + /* Free PFI lines */ + xseries_free_pfi_lines(trig_fd, 0XFFFF); + + /* reset segment */ + xseries_reset_dio(dio_fd); + xseries_reset_pfi(pfi_fd); + + /* close segment's file descriptor */ + close(dio_fd); + close(pfi_fd); + + return retval; +} + +void print_text(void){ + printf ("\n"); + + printf("Test software-timed, static DIO and PFI operation using DIO and PFI ports.\n"); + printf ("\n"); +} + +int main (int argc, char** argv) { + + int retval = 0; + char * device_name; + int silent = false; + + if (argc == 2) { + device_name = argv[1]; + print_text(); + } else if (argc == 3) { + device_name = argv[1]; + if(strcmp(argv[2],"-silent") != 0) { + print_text(); + silent = false; + } else { + silent = true; + } + } else { + printf ("Usage: %s \n", argv[0]); + printf ("Example:\n %s /dev/pxie-6368.0\n", argv[0]); + printf ("\n"); + exit(EXIT_FAILURE); + } + + if (silent) { + printf("%-10s%-100s", + argv[0], + "Test software-timed, static DIO and PFI operation using DIO and PFI ports."); + fflush(stdout); + } + + /* run test */ + retval = test(device_name,silent); + + if (!silent) { + printf("Test: "); + fflush(stdout); + } + + printf("[%s]\n",retval!=0? "FAILED":"OK"); + + if(!silent) { printf ("\n");} + + return retval; +} + diff --git a/device_support/ptgrey/PTGREY.cpp b/device_support/ptgrey/PTGREY.cpp index 1f8c35e0c2..51bffa03aa 100644 --- a/device_support/ptgrey/PTGREY.cpp +++ b/device_support/ptgrey/PTGREY.cpp @@ -36,10 +36,11 @@ using namespace MDSplus; #include #include + #include #include -#define BUFFER_COUNT 16 +#define BUFFER_COUNT 16 #define ERROR -1 #define SUCCESS 0 @@ -47,473 +48,496 @@ using namespace MDSplus; //if defined, print to stdout messages. #define debug + #define MAX_CAM 10 static PTGREY *camPtr[MAX_CAM] = {0}; static char errorOnOpen[512]; -#ifdef __cplusplus -extern "C" -{ -#endif - int PGopen(const char *ipAddress, int *camHandle) - { - PTGREY *cam; - int cameraHandle; +#ifdef __cplusplus +extern "C" +{ +#endif - errorOnOpen[0] = 0; - cam = new PTGREY(ipAddress); - if (!cam->checkLastOp()) - { - cam->getLastError(errorOnOpen); - delete (cam); - return ERROR; - } +int PGopen(const char *ipAddress, int *camHandle) +{ + PTGREY *cam; + int cameraHandle; + + errorOnOpen[0] = 0; + + cam = new PTGREY(ipAddress); + if(!cam->checkLastOp()) + { + cam->getLastError(errorOnOpen); + delete(cam); + return ERROR; + } + + for( cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle] ; cameraHandle++); + + if( cameraHandle < MAX_CAM ) + { + camPtr[cameraHandle] = cam; + *camHandle = cameraHandle; + return SUCCESS; + } + else + { + sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); + *camHandle = -1; + return ERROR; + } +} - for (cameraHandle = 0; cameraHandle < MAX_CAM && camPtr[cameraHandle]; cameraHandle++) - ; - if (cameraHandle < MAX_CAM) - { - camPtr[cameraHandle] = cam; - *camHandle = cameraHandle; - return SUCCESS; - } - else - { - sprintf(errorOnOpen, "Exceed maximum number (10) of opened cameras "); - *camHandle = -1; - return ERROR; - } - } +int isConnected( int camHandle ) +{ + if( camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0 ) + { + sprintf(errorOnOpen, "Camera does not connect"); + return ERROR; + } + return SUCCESS; +} - int isConnected(int camHandle) - { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) - { - sprintf(errorOnOpen, "Camera does not connect"); - return ERROR; - } - return SUCCESS; - } +int PGclose(int camHandle) +{ + delete(camPtr[camHandle]); + camPtr[camHandle] = 0; + + return SUCCESS; +} - int PGclose(int camHandle) - { - delete (camPtr[camHandle]); - camPtr[camHandle] = 0; - return SUCCESS; - } +int checkLastOp(int camHandle) +{ + return camPtr[camHandle]->checkLastOp(); +} - int checkLastOp(int camHandle) - { - return camPtr[camHandle]->checkLastOp(); - } - int printAllParameters(int camHandle) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->printAllParameters(); - return ERROR; - } +int printAllParameters(int camHandle) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->printAllParameters(); + return ERROR; +} - int readInternalTemperature(int camHandle) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->readInternalTemperature(); - return ERROR; - } - int setExposure(int camHandle, float exposure) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setExposure(exposure); - return ERROR; - } +int readInternalTemperature(int camHandle) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->readInternalTemperature(); + return ERROR; +} - int setExposureAuto(int camHandle, char *exposureAuto) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setExposureAuto(exposureAuto); - return ERROR; - } +int setExposure(int camHandle, float exposure) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setExposure(exposure); + return ERROR; +} - int setGain(int camHandle, float gain) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setGain(gain); - return ERROR; - } - int setGainAuto(int camHandle, char *gainAuto) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setGainAuto(gainAuto); - return ERROR; - } +int setExposureAuto(int camHandle, char *exposureAuto) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setExposureAuto(exposureAuto); + return ERROR; +} - int setGammaEnable(int camHandle, char *gammaEnable) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setGammaEnable(gammaEnable); - return ERROR; - } - int setFrameRate(int camHandle, double *frameRate) - { - if (isConnected(camHandle) == SUCCESS) - { - double fRate; - int status; - fRate = *frameRate; - status = camPtr[camHandle]->setFrameRate(fRate); - *frameRate = fRate; - return status; - } - return ERROR; - } +int setGain(int camHandle, float gain) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setGain(gain); + return ERROR; +} - int setReadoutArea(int camHandle, int x, int y, int width, int height) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setReadoutArea(x, y, width, height); - return ERROR; - } - int setPixelFormat(int camHandle, char *pixelFormat) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setPixelFormat(pixelFormat); - return ERROR; - } +int setGainAuto(int camHandle, char *gainAuto) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setGainAuto(gainAuto); + return ERROR; +} - int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startAcquisition(width, height, payloadSize); - return ERROR; - } - int stopAcquisition(int camHandle) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopAcquisition(); - return ERROR; - } +int setGammaEnable(int camHandle, char *gammaEnable) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setGammaEnable(gammaEnable); + return ERROR; +} - int getFrame(int camHandle, int *status, void *frame, void *metaData) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->getFrame(status, frame, metaData); - return ERROR; - } - int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber) +int setFrameRate(int camHandle, double *frameRate) +{ + if( isConnected( camHandle ) == SUCCESS ) { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setAcquisitionMode(storeEnabled, acqSkipFrameNumber); - return ERROR; + double fRate; + int status; + fRate = *frameRate; + status = camPtr[camHandle]->setFrameRate(fRate); + *frameRate = fRate; + return status; } + return ERROR; +} - int setTriggerMode(int camHandle, int triggerMode, double burstDuration, int numTrigger) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTriggerMode(triggerMode, burstDuration, numTrigger); - return ERROR; - } - int softwareTrigger(int camHandle) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->softwareTrigger(); - return ERROR; - } +int setReadoutArea(int camHandle, int x, int y, int width, int height) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setReadoutArea(x, y, width, height); + return ERROR; +} - int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setTreeInfo(treePtr, framesNid, timebaseNid, framesMetadNid, frame0TimeNid); - return ERROR; - } - int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, - const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->setStreamingMode(streamingEnabled, autoAdjustLimit, streamingServer, streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); - return ERROR; - } - int startFramesAcquisition(int camHandle) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->startFramesAcquisition(); - return ERROR; - } +int setPixelFormat(int camHandle, char *pixelFormat) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setPixelFormat(pixelFormat); + return ERROR; +} - int stopFramesAcquisition(int camHandle) - { - if (isConnected(camHandle) == SUCCESS) - return camPtr[camHandle]->stopFramesAcquisition(); - return ERROR; - } - void getLastError(int camHandle, char *msg) - { - if (camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0) - { - sprintf(msg, "%s", (errorOnOpen[0] == 0) ? "" : errorOnOpen); - return; - } - camPtr[camHandle]->getLastError(msg); - } +int startAcquisition(int camHandle, int *width, int *height, int *payloadSize) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->startAcquisition(width, height, payloadSize); + return ERROR; +} + -#ifdef __cplusplus +int stopAcquisition(int camHandle) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->stopAcquisition(); + return ERROR; } -#endif -PTGREY::PTGREY(const char *ipAddress) + +int getFrame(int camHandle, int *status, void *frame, void *metaData) { - this->ipAddress = PvString(ipAddress); - trigEvent = NULL; + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->getFrame(status, frame, metaData); + return ERROR; +} - /* SDK 3 - this->lDevice = new PvDevice(); - this->lResult = this->lDevice->Connect(this->ipAddress, PvAccessExclusive); -*/ - try - { - this->lDevice = PvDevice::CreateAndConnect(this->ipAddress, &this->lResult); //20160309 SDK4 //sometimes goes in coredump - } - catch (...) - { - printf("Core dump detected on PvDevice::CreateAndConnect\n"); - } - if (!this->lResult.IsOK()) - { - printf("--------------------------------- Error Device connection: (%s) %p\n", this->lResult.GetCodeString().GetAscii(), this->lDevice); - if (this->lDevice != nullptr) //CT 2019-03-29 - { - PvDevice::Free(this->lDevice); - } - } - else - { - printf("---------------------------- OK Device connection: (%s)\n", this->lResult.GetDescription().GetAscii()); - } - printf("EVENTO abilitato \n"); - //CT MDSplus acquisition Triggered on MDSevent - eventTrigger = 0; - trigEvent = new TriggerMdsEvent("__CCD_TRIGGER__", this); - trigEvent->start(); +int setAcquisitionMode( int camHandle, int storeEnabled, int acqSkipFrameNumber) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setAcquisitionMode( storeEnabled, acqSkipFrameNumber); + return ERROR; } -PTGREY::PTGREY() //new 25/07/2013: let to use the device without the camera +int setTriggerMode( int camHandle, int triggerMode, double burstDuration, int numTrigger ) { - //this->lDevice = new PvDevice(); //SDK 3 - //SDK 4 09/03/2016 NON sembra possibile creare un PVDEVICE se non ho la telecamera + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setTriggerMode( triggerMode, burstDuration, numTrigger ); + return ERROR; } -PTGREY::~PTGREY() +int softwareTrigger(int camHandle) { + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->softwareTrigger(); + return ERROR; +} - printf("PTGREY destructor %p\n", this->lDevice); - if (this->lDevice != nullptr) //CT 2019-03-27 - { - this->lResult = this->lDevice->Disconnect(); - if (!this->lResult.IsOK()) - printLastError("Error Device disconnection !!!\n(%s)\n", lResult.GetDescription().GetAscii()); - else - printf("PTGREY destructor class executed\n"); - //delete(this->lDevice); //SDK 3 - PvDevice::Free(this->lDevice); //SDK 4 09/03/2016 - } +int setTreeInfo( int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setTreeInfo( treePtr, framesNid, timebaseNid, framesMetadNid, frame0TimeNid ); + return ERROR; +} + +int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, + const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->setStreamingMode(streamingEnabled, autoAdjustLimit, streamingServer, streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, deviceName); + return ERROR; - if (trigEvent != NULL) - delete trigEvent; +} +int startFramesAcquisition(int camHandle) +{ + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->startFramesAcquisition(); + return ERROR; } -int PTGREY::checkLastOp() +int stopFramesAcquisition(int camHandle) { - printf("Info %d (%s)\n", this->lResult.IsOK(), lResult.GetDescription().GetAscii()); - if (!this->lResult.IsOK()) - printLastError("(%s)\n", lResult.GetDescription().GetAscii()); - return this->lResult.IsOK(); + if( isConnected( camHandle ) == SUCCESS ) + return camPtr[camHandle]->stopFramesAcquisition(); + return ERROR; } -int PTGREY::printAllParameters() +void getLastError(int camHandle, char *msg) { - PvGenParameterArray *aArray = lDevice->GetParameters(); - uint32_t lParameterArrayCount = aArray->GetCount(); - printf("\nArray has %d parameters\n", lParameterArrayCount); + if( camHandle < 0 || camHandle >= MAX_CAM || camPtr[camHandle] == 0 ) + { + sprintf(msg, "%s", (errorOnOpen[0]==0) ? "" : errorOnOpen); + return; + } + camPtr[camHandle]->getLastError(msg); +} - // Traverse through Array and print out parameters available - for (uint32_t x = 0; x < lParameterArrayCount; x++) - { - // Get a parameter - PvGenParameter *lGenParameter = aArray->Get(x); - // Don't show invisible parameters - display everything up to Guru - if (!lGenParameter->IsVisible(PvGenVisibilityGuru)) - { - continue; - } +#ifdef __cplusplus +} +#endif - // Get and print parameter's name - PvString lGenParameterName, lCategory; - lGenParameter->GetCategory(lCategory); - lGenParameter->GetName(lGenParameterName); - printf("%s:%s, ", lCategory.GetAscii(), lGenParameterName.GetAscii()); - // Parameter available? - if (!lGenParameter->IsAvailable()) - { - printf("{Not Available}\n"); - continue; - } - // Parameter readable? - if (!lGenParameter->IsReadable()) - { - printf("{Not readable}\n"); - continue; - } - // Get the parameter type - PvGenType lType; - lGenParameter->GetType(lType); - switch (lType) - { - // If the parameter is of type PvGenTypeInteger - case PvGenTypeInteger: - { - int64_t lValue; - static_cast(lGenParameter)->GetValue(lValue); - printf("Integer: %d", lValue); +PTGREY::PTGREY(const char *ipAddress) +{ + this->ipAddress = PvString(ipAddress); + trigEvent = NULL; + +/* SDK 3 + this->lDevice = new PvDevice(); + this->lResult = this->lDevice->Connect(this->ipAddress, PvAccessExclusive); +*/ + try{ + this->lDevice = PvDevice::CreateAndConnect(this->ipAddress, &this->lResult); //20160309 SDK4 //sometimes goes in coredump } - break; - // If the parameter is of type PvGenTypeEnum - case PvGenTypeEnum: + catch(...) { - PvString lValue; - static_cast(lGenParameter)->GetValue(lValue); - printf("Enum: %s", lValue.GetAscii()); + printf("Core dump detected on PvDevice::CreateAndConnect\n"); } - break; - // If the parameter is of type PvGenTypeBoolean - case PvGenTypeBoolean: + if ( !this->lResult.IsOK() ) { - bool lValue; - static_cast(lGenParameter)->GetValue(lValue); - if (lValue) - { - printf("Boolean: TRUE"); - } - else - { - printf("Boolean: FALSE"); - } + printf("--------------------------------- Error Device connection: (%s) %p\n", this->lResult.GetCodeString().GetAscii(), this->lDevice); + if( this->lDevice != nullptr ) //CT 2019-03-29 + { + PvDevice::Free(this->lDevice); + } } - break; - // If the parameter is of type PvGenTypeString - case PvGenTypeString: - { - PvString lValue; - static_cast(lGenParameter)->GetValue(lValue); - printf("String: %s", lValue.GetAscii()); + else + { + printf("---------------------------- OK Device connection: (%s)\n", this->lResult.GetDescription().GetAscii() ); } - break; - // If the parameter is of type PvGenTypeCommand - case PvGenTypeCommand: - printf("Command"); - break; - // If the parameter is of type PvGenTypeFloat - case PvGenTypeFloat: + + printf("EVENTO abilitato \n"); + //CT MDSplus acquisition Triggered on MDSevent + eventTrigger = 0; + trigEvent = new TriggerMdsEvent("__CCD_TRIGGER__", this); + trigEvent->start(); + +} + + +PTGREY::PTGREY() //new 25/07/2013: let to use the device without the camera +{ + //this->lDevice = new PvDevice(); //SDK 3 + //SDK 4 09/03/2016 NON sembra possibile creare un PVDEVICE se non ho la telecamera +} + + +PTGREY::~PTGREY() +{ + + printf("PTGREY destructor %p\n", this->lDevice ); + if( this->lDevice != nullptr ) //CT 2019-03-27 { - double lValue; - static_cast(lGenParameter)->GetValue(lValue); - printf("Float: %f", lValue); - } - break; + this->lResult = this->lDevice->Disconnect(); + if ( !this->lResult.IsOK() ) + printLastError("Error Device disconnection !!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + else + printf("PTGREY destructor class executed\n"); + //delete(this->lDevice); //SDK 3 + PvDevice::Free(this->lDevice); //SDK 4 09/03/2016 } - printf("\n"); - } - return SUCCESS; + if( trigEvent != NULL ) + delete trigEvent; + +} + + + +int PTGREY::checkLastOp() +{ + printf("Info %d (%s)\n", this->lResult.IsOK(), lResult.GetDescription().GetAscii() ); + if ( !this->lResult.IsOK() ) + printLastError("(%s)\n", lResult.GetDescription().GetAscii() ); + return this->lResult.IsOK(); +} + + + +int PTGREY::printAllParameters() +{ + PvGenParameterArray *aArray = lDevice->GetParameters(); + uint32_t lParameterArrayCount = aArray->GetCount(); + printf( "\nArray has %d parameters\n", lParameterArrayCount ); + + // Traverse through Array and print out parameters available + for( uint32_t x = 0; x < lParameterArrayCount; x++ ) + { + // Get a parameter + PvGenParameter *lGenParameter = aArray->Get( x ); + + // Don't show invisible parameters - display everything up to Guru + if ( !lGenParameter->IsVisible( PvGenVisibilityGuru ) ) + { + continue; + } + + // Get and print parameter's name + PvString lGenParameterName, lCategory; + lGenParameter->GetCategory( lCategory ); + lGenParameter->GetName( lGenParameterName ); + printf( "%s:%s, ", lCategory.GetAscii(), lGenParameterName.GetAscii() ); + + // Parameter available? + if ( !lGenParameter->IsAvailable() ) + { + printf( "{Not Available}\n" ); + continue; + } + + // Parameter readable? + if ( !lGenParameter->IsReadable() ) + { + printf( "{Not readable}\n" ); + continue; + } + + // Get the parameter type + PvGenType lType; + lGenParameter->GetType( lType ); + switch ( lType ) + { + // If the parameter is of type PvGenTypeInteger + case PvGenTypeInteger: + { + int64_t lValue; + static_cast( lGenParameter )->GetValue( lValue ); + printf( "Integer: %d", lValue ); + } + break; + // If the parameter is of type PvGenTypeEnum + case PvGenTypeEnum: + { + PvString lValue; + static_cast( lGenParameter )->GetValue( lValue ); + printf( "Enum: %s", lValue.GetAscii() ); + } + break; + // If the parameter is of type PvGenTypeBoolean + case PvGenTypeBoolean: + { + bool lValue; + static_cast( lGenParameter )->GetValue( lValue ); + if( lValue ) + { + printf( "Boolean: TRUE" ); + } + else + { + printf( "Boolean: FALSE" ); + } + } + break; + // If the parameter is of type PvGenTypeString + case PvGenTypeString: + { + PvString lValue; + static_cast( lGenParameter )->GetValue( lValue ); + printf( "String: %s", lValue.GetAscii() ); + } + break; + // If the parameter is of type PvGenTypeCommand + case PvGenTypeCommand: + printf( "Command" ); + break; + // If the parameter is of type PvGenTypeFloat + case PvGenTypeFloat: + { + double lValue; + static_cast( lGenParameter )->GetValue( lValue ); + printf( "Float: %f", lValue ); + } + break; + } + printf("\n"); + } + + return SUCCESS; } + int PTGREY::readInternalTemperature() { - double t; - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenFloat *linternalTemp = dynamic_cast(lDeviceParams->Get("DeviceTemperature")); - this->lResult = linternalTemp->GetValue(t); - if (!this->lResult.IsOK()) - { - printLastError("Error reading Internal Temperature!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + double t; + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenFloat *linternalTemp = dynamic_cast( lDeviceParams->Get( "DeviceTemperature" ) ); + this->lResult = linternalTemp->GetValue( t ); + if ( !this->lResult.IsOK() ) + {printLastError("Error reading Internal Temperature!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - this->internalTemperature = t; //t must be double but is a float - printf("%s: Camera Temperature is now %3.2f°C\n", (this->ipAddress).GetAscii(), this->internalTemperature); + this->internalTemperature=t; //t must be double but is a float + printf("%s: Camera Temperature is now %3.2f°C\n", (this->ipAddress).GetAscii(), this->internalTemperature); return SUCCESS; } -int PTGREY::setExposure(float exposure) //[us] - Min: 15 Max: 3e+07 attenzione double-float + +int PTGREY::setExposure(float exposure) //[us] - Min: 15 Max: 3e+07 attenzione double-float { PvString lValue; PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenEnum *lExposureAuto = dynamic_cast(lDeviceParams->Get("ExposureAuto")); - if (exposure < 15.0 or exposure > 30000000.0) + PvGenEnum *lExposureAuto = dynamic_cast( lDeviceParams->Get( "ExposureAuto" ) ); + if(exposure<15.0 or exposure>30000000.0) { printf("ERROR: exposure should be in range 15.0 - 3e+07 [us]...\n"); return ERROR; } - this->lResult = lExposureAuto->GetValue(lValue); - if (strcmp(lValue.GetAscii(), "Off") == 0) + this->lResult = lExposureAuto->GetValue( lValue ); + if(strcmp(lValue.GetAscii(), "Off")==0) { PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenFloat *lExposure = dynamic_cast(lDeviceParams->Get("ExposureTime")); - this->lResult = lExposure->SetValue(exposure); - if (!this->lResult.IsOK()) - { - printLastError("Error setting exposure!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + PvGenFloat *lExposure = dynamic_cast( lDeviceParams->Get( "ExposureTime" ) ); + this->lResult = lExposure->SetValue( exposure ); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting exposure!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} } else { printf("WARNING: to set the exposure value the ExposureAuto must be Off\n"); } - this->exposure = exposure; - printf("%s: Exposure set to %.1fus\n", (this->ipAddress).GetAscii(), exposure); + this->exposure=exposure; + printf("%s: Exposure set to %.1fus\n", (this->ipAddress).GetAscii(), exposure); return SUCCESS; } + int PTGREY::setExposureAuto(char *exposureAuto) { - if (strcmp(exposureAuto, "Off") != 0 & strcmp(exposureAuto, "Once") != 0 & strcmp(exposureAuto, "Continuous") != 0) + if(strcmp(exposureAuto, "Off")!=0 & strcmp(exposureAuto, "Once")!=0 & strcmp(exposureAuto, "Continuous")!=0) { printf("ERROR: setExposureAuto must be Off, Once or Continuous\n"); return ERROR; } - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - this->lResult = lDeviceParams->SetEnumValue("ExposureAuto", exposureAuto); - if (!this->lResult.IsOK()) - { - printLastError("Error setting exposureAuto!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + this->lResult = lDeviceParams->SetEnumValue( "ExposureAuto", exposureAuto ); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting exposureAuto!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} return SUCCESS; } int PTGREY::setGammaEnable(char *gammaEnable) { - /* +/* if(strcmp(gammaEnable, "On")==0) { pCamera->GammaEnable.SetValue(true); @@ -522,115 +546,97 @@ int PTGREY::setGammaEnable(char *gammaEnable) { pCamera->GammaEnable.SetValue(false); } -*/ - printf("%s: setGammaEnable BYPASSED 4 TEST\n", (this->ipAddress).GetAscii()); +*/ + printf("%s: setGammaEnable BYPASSED 4 TEST\n", (this->ipAddress).GetAscii()); return SUCCESS; } -int PTGREY::setGain(float gain) //Off impostabile solo in gainAuto=Off +int PTGREY::setGain(float gain) //Off impostabile solo in gainAuto=Off { PvString lValue; PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenEnum *lGainAuto = dynamic_cast(lDeviceParams->Get("GainAuto")); - if (gain < 0.0 or gain > 47.9943) + PvGenEnum *lGainAuto = dynamic_cast( lDeviceParams->Get( "GainAuto" ) ); + if(gain<0.0 or gain>47.9943) { printf("ERROR: gain should be in range 0.0 - 47.9943 [dB]...\n"); return ERROR; } - this->lResult = lGainAuto->GetValue(lValue); - if (strcmp(lValue.GetAscii(), "Off") == 0) + this->lResult = lGainAuto->GetValue( lValue ); + if(strcmp(lValue.GetAscii(), "Off")==0) { PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenFloat *lGain = dynamic_cast(lDeviceParams->Get("Gain")); - this->lResult = lGain->SetValue(gain); - if (!this->lResult.IsOK()) - { - printLastError("Error setting gain!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + PvGenFloat *lGain = dynamic_cast( lDeviceParams->Get( "Gain" ) ); + this->lResult = lGain->SetValue( gain ); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting gain!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} } else { printf("WARNING: to set the gain value the gainAuto must be Off\n"); } - this->gain = gain; - printf("%s: Gain set to %.2fdB\n", (this->ipAddress).GetAscii(), gain); + this->gain=gain; + printf("%s: Gain set to %.2fdB\n", (this->ipAddress).GetAscii(), gain); return SUCCESS; } -int PTGREY::setGainAuto(char *gainAuto) //Off(0), Once(1), Continuous(2) + +int PTGREY::setGainAuto(char *gainAuto) //Off(0), Once(1), Continuous(2) { - if (strcmp(gainAuto, "Off") != 0 & strcmp(gainAuto, "Once") != 0 & strcmp(gainAuto, "Continuous") != 0) + if(strcmp(gainAuto, "Off")!=0 & strcmp(gainAuto, "Once")!=0 & strcmp(gainAuto, "Continuous")!=0) { printf("ERROR: setGainAuto must be Off, Once or Continuous\n"); return ERROR; } - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - this->lResult = lDeviceParams->SetEnumValue("GainAuto", gainAuto); - if (!this->lResult.IsOK()) - { - printLastError("Error setting gainAuto!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + this->lResult = lDeviceParams->SetEnumValue( "GainAuto", gainAuto ); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting gainAuto!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} return SUCCESS; } + + int PTGREY::setFrameRate(double &frameRate) { PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenBoolean *sFrameRateEn = dynamic_cast(lDeviceParams->Get("AcquisitionFrameRateEnable")); - if (frameRate < 1.0 or frameRate > 39.2221) + PvGenBoolean *sFrameRateEn = dynamic_cast( lDeviceParams->Get("AcquisitionFrameRateEnable")); + if(frameRate<1.0 or frameRate>39.2221) { - double resFrameRate; + double resFrameRate; - this->lResult = sFrameRateEn->SetValue(0); - if (!this->lResult.IsOK()) - { - printLastError("Error setting AcquisitionFrameRateEnable in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); + this->lResult = sFrameRateEn->SetValue( 0 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting AcquisitionFrameRateEnable in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + usleep(3000); - PvGenFloat *sResFrameRate = dynamic_cast(lDeviceParams->Get("AcquisitionResultingFrameRate")); - this->lResult = sResFrameRate->GetValue(resFrameRate); - if (!this->lResult.IsOK()) - { - printLastError("Error setting AcquisitionResultingFrameRate in getFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + PvGenFloat *sResFrameRate = dynamic_cast( lDeviceParams->Get("AcquisitionResultingFrameRate")); + this->lResult = sResFrameRate->GetValue( resFrameRate ); - printf("%s: Resulting Framerate %f fps\n", (this->ipAddress).GetAscii(), resFrameRate); + if ( !this->lResult.IsOK() ) {printLastError("Error setting AcquisitionResultingFrameRate in getFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + printf("%s: Resulting Framerate %f fps\n", (this->ipAddress).GetAscii(), resFrameRate); - this->frameRate = resFrameRate; + this->frameRate = resFrameRate; - frameRate = resFrameRate; + frameRate = resFrameRate; //printf("ERROR: frameRate should be in range 1.0 - 39.2221 [Hz]...\n"); return SUCCESS; } - this->lResult = sFrameRateEn->SetValue(1); - if (!this->lResult.IsOK()) - { - printLastError("Error setting AcquisitionFrameRateEnable in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - - PvGenFloat *sFrameRate = dynamic_cast(lDeviceParams->Get("AcquisitionFrameRate")); - this->lResult = sFrameRate->SetValue((float)frameRate); - if (!this->lResult.IsOK()) - { - printLastError("Error setting AcquisitionFrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + this->lResult = sFrameRateEn->SetValue( 1 ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting AcquisitionFrameRateEnable in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + usleep(3000); + + PvGenFloat *sFrameRate = dynamic_cast( lDeviceParams->Get("AcquisitionFrameRate")); + this->lResult = sFrameRate->SetValue( (float)frameRate ); + if ( !this->lResult.IsOK() ) {printLastError("Error setting AcquisitionFrameRate in setFrameRate!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} usleep(3000); this->frameRate = frameRate; - printf("%s: Framerate set to %.2ffps\n", (this->ipAddress).GetAscii(), frameRate); + printf("%s: Framerate set to %.2ffps\n", (this->ipAddress).GetAscii(), frameRate); return SUCCESS; } @@ -673,303 +679,255 @@ usleep(3000); } */ + int PTGREY::setReadoutArea(int x, int y, int width, int height) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lWidth = dynamic_cast(lDeviceParams->Get("Width")); - PvGenInteger *lHeight = dynamic_cast(lDeviceParams->Get("Height")); - PvGenInteger *lOffsetX = dynamic_cast(lDeviceParams->Get("OffsetX")); - PvGenInteger *lOffsetY = dynamic_cast(lDeviceParams->Get("OffsetY")); - - this->lResult = lWidth->SetValue(width); - if (!this->lResult.IsOK()) - { - printLastError("Error setting Width in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - // this->lResult = lHeight->SetValue(h+3); //add 3 lines of metadata - this->lResult = lHeight->SetValue(height); //add 3 lines of metadata - if (!this->lResult.IsOK()) - { - printLastError("Error setting Height in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lOffsetX->SetValue(x); - if (!this->lResult.IsOK()) - { - printLastError("Error setting OffsetX in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - usleep(3000); - this->lResult = lOffsetY->SetValue(y); - if (!this->lResult.IsOK()) - { - printLastError("Error setting OffsetY in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - - this->x = x; - this->y = y; - this->width = width; - this->height = height; - - return SUCCESS; + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lWidth = dynamic_cast( lDeviceParams->Get( "Width" ) ); + PvGenInteger *lHeight = dynamic_cast( lDeviceParams->Get( "Height" ) ); + PvGenInteger *lOffsetX = dynamic_cast( lDeviceParams->Get( "OffsetX" ) ); + PvGenInteger *lOffsetY = dynamic_cast( lDeviceParams->Get( "OffsetY" ) ); + + this->lResult = lWidth->SetValue(width); + if ( !this->lResult.IsOK() ) {printLastError("Error setting Width in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + usleep(3000); +// this->lResult = lHeight->SetValue(h+3); //add 3 lines of metadata + this->lResult = lHeight->SetValue(height); //add 3 lines of metadata + if ( !this->lResult.IsOK() ) {printLastError("Error setting Height in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + usleep(3000); + this->lResult = lOffsetX->SetValue(x); + if ( !this->lResult.IsOK() ) {printLastError("Error setting OffsetX in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + usleep(3000); + this->lResult = lOffsetY->SetValue(y); + if ( !this->lResult.IsOK() ) {printLastError("Error setting OffsetY in setReadoutArea\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + + this->x = x; + this->y = y; + this->width = width; + this->height = height; + + return SUCCESS; } -int PTGREY::setPixelFormat(char *pixelFormat) //Enum: Mono8 - Mono16 (others not used: Mono10Packed, Mono12Packed) + +int PTGREY::setPixelFormat(char *pixelFormat) //Enum: Mono8 - Mono16 (others not used: Mono10Packed, Mono12Packed) { - if (strcmp(pixelFormat, "Mono8") != 0 & strcmp(pixelFormat, "Mono16") != 0) + if(strcmp(pixelFormat, "Mono8")!=0 & strcmp(pixelFormat, "Mono16")!=0) { printf("ERROR: PixelFormat must be Mono8 or Mono16\n"); return ERROR; } - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - this->lResult = lDeviceParams->SetEnumValue("PixelFormat", pixelFormat); - if (!this->lResult.IsOK()) - { - printLastError("Error setting PixelFormat!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + this->lResult = lDeviceParams->SetEnumValue( "PixelFormat", pixelFormat ); + if ( !this->lResult.IsOK() ) + {printLastError("Error setting PixelFormat!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - if (strcmp(pixelFormat, "Mono8") == 0) + if(strcmp(pixelFormat, "Mono8")==0) { - this->pixelFormat = CSU_PIX_FMT_GRAY8; - this->Bpp = 1; + this->pixelFormat = CSU_PIX_FMT_GRAY8; + this->Bpp = 1; } - if (strcmp(pixelFormat, "Mono16") == 0) + if(strcmp(pixelFormat, "Mono16")==0) { - this->pixelFormat = CSU_PIX_FMT_GRAY16; - this->Bpp = 2; + this->pixelFormat = CSU_PIX_FMT_GRAY16; + this->Bpp = 2; } - printf("%s: PixelFormat set to %s\n", (this->ipAddress).GetAscii(), pixelFormat); + printf("%s: PixelFormat set to %s\n", (this->ipAddress).GetAscii(), pixelFormat); return SUCCESS; } + int PTGREY::startAcquisition(int *width, int *height, int *payloadSize) { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lTLLocked = dynamic_cast(lDeviceParams->Get("TLParamsLocked")); - PvGenInteger *lWidth = dynamic_cast(lDeviceParams->Get("Width")); - PvGenInteger *lHeight = dynamic_cast(lDeviceParams->Get("Height")); - PvGenInteger *lPayloadSize = dynamic_cast(lDeviceParams->Get("PayloadSize")); - PvGenCommand *lResetTimestamp = dynamic_cast(lDeviceParams->Get("GevTimestampControlReset")); - PvGenCommand *lStart = dynamic_cast(lDeviceParams->Get("AcquisitionStart")); - - // Get stream parameters/stats - //17-10-2016: segmentation fault with SDK4. to check! - /* + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lTLLocked = dynamic_cast( lDeviceParams->Get( "TLParamsLocked" ) ); + PvGenInteger *lWidth = dynamic_cast( lDeviceParams->Get( "Width" ) ); + PvGenInteger *lHeight = dynamic_cast( lDeviceParams->Get( "Height" ) ); + PvGenInteger *lPayloadSize = dynamic_cast( lDeviceParams->Get( "PayloadSize" ) ); + PvGenCommand *lResetTimestamp = dynamic_cast( lDeviceParams->Get( "GevTimestampControlReset" ) ); + PvGenCommand *lStart = dynamic_cast( lDeviceParams->Get( "AcquisitionStart" ) ); + + // Get stream parameters/stats +//17-10-2016: segmentation fault with SDK4. to check! +/* PvGenParameterArray *lStreamParams = lStream->GetParameters(); PvGenInteger *lCount = dynamic_cast( lStreamParams->Get( "ImagesCount" ) ); PvGenFloat *lFrameRate = dynamic_cast( lStreamParams->Get( "AcquisitionRateAverage" ) ); PvGenFloat *lBandwidth = dynamic_cast( lStreamParams->Get( "BandwidthAverage" ) ); */ - PvGenInteger *lTickFreq = dynamic_cast(lDeviceParams->Get("GevTimestampTickFrequency")); - this->lResult = lTickFreq->GetValue(tickFreq); - if (!this->lResult.IsOK()) - { - printLastError("Error getting GevTimestampTickFrequency in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - } - //printf("---> GevTimestampTickFrequency = %d\n", tickFreq); - int64_t w = 0; - int64_t h = 0; - int64_t lSize = 0; + PvGenInteger *lTickFreq = dynamic_cast( lDeviceParams->Get( "GevTimestampTickFrequency" ) ); + this->lResult = lTickFreq->GetValue( tickFreq ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting GevTimestampTickFrequency in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() );} + //printf("---> GevTimestampTickFrequency = %d\n", tickFreq); - this->lResult = lWidth->GetValue(w); - if (!this->lResult.IsOK()) - { - printLastError("Error getting frame width in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - this->lResult = lHeight->GetValue(h); - if (!this->lResult.IsOK()) - { - printLastError("Error getting frame height in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - this->lResult = lPayloadSize->GetValue(lSize); - if (!this->lResult.IsOK()) - { - printLastError("Error getting payload size in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + int64_t w = 0; + int64_t h = 0; + int64_t lSize = 0; + + this->lResult = lWidth->GetValue( w ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting frame width in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + this->lResult = lHeight->GetValue( h ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting frame height in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + this->lResult = lPayloadSize->GetValue( lSize ); + if ( !this->lResult.IsOK() ) {printLastError("Error getting payload size in startAcquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - this->width = *width = (int)w; - // this->height = *height= (int)h-3; //first 3 rows are metadata - this->height = *height = (int)h; + this->width = *width = (int)w; +// this->height = *height= (int)h-3; //first 3 rows are metadata + this->height = *height= (int)h; - *payloadSize = lSize; //payload = width*height*2 + metadata - printf("w:%d h:%d p:%d\n", this->width, this->height, (int)lSize); - /* + *payloadSize=lSize; //payload = width*height*2 + metadata + printf("w:%d h:%d p:%d\n", this->width, this->height, (int)lSize); +/* new 09 mar 2016 for SDK4 // If this is a GigE Vision device, configure GigE Vision specific streaming parameters */ - PvDeviceGEV *lDeviceGEV = static_cast(this->lDevice); - //17-10-2016 lStreamGEV moved down - /* + PvDeviceGEV *lDeviceGEV = static_cast( this->lDevice ); + //17-10-2016 lStreamGEV moved down +/* end new */ - // Negotiate streaming packet size - //this->lResult = lDevice->NegotiatePacketSize(); //SDK 3 - this->lResult = lDeviceGEV->NegotiatePacketSize(); //SDK 4 + // Negotiate streaming packet size + //this->lResult = lDevice->NegotiatePacketSize(); //SDK 3 + this->lResult = lDeviceGEV->NegotiatePacketSize(); //SDK 4 - if (!this->lResult.IsOK()) - { - printLastError("Error negotiating packet size in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - - PvGenInteger *lPacketSize = dynamic_cast(lDevice->GetParameters()->Get("GevSCPSPacketSize")); + if ( !this->lResult.IsOK() ) + { + printLastError("Error negotiating packet size in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + return ERROR; + } - int64_t lPacketSizeValue = 0; - lResult = lPacketSize->GetValue(lPacketSizeValue); - if (!lResult.IsOK()) - { - printLastError("FATAL ERROR: Unable to read packet size!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - //fprintf( stderr, "FATAL ERROR: Unable to read packet size\n" ); - } + PvGenInteger *lPacketSize = dynamic_cast( lDevice->GetParameters()->Get( "GevSCPSPacketSize" ) ); - printf("--------> lPacketSizeValue %d\n", lPacketSizeValue); + int64_t lPacketSizeValue = 0; + lResult = lPacketSize->GetValue( lPacketSizeValue ); + if ( !lResult.IsOK() ) + { + printLastError("FATAL ERROR: Unable to read packet size!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + return ERROR; + //fprintf( stderr, "FATAL ERROR: Unable to read packet size\n" ); + } + printf("--------> lPacketSizeValue %d\n", lPacketSizeValue); + // PvString aID; - // this->lResult = lDevice->GetUniqueID(aID); - - // Open stream - //this->lResult = this->lStream->Open( this->ipAddress); //SDK 3 - this->lStream = NULL; - - //this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); //20160309 SDK4 - this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); //20160309 SDK4 - - //if ( ( this->lStream == NULL ) || !this->lResult.IsOK() ) - if (this->lStream == NULL) - { - printLastError("Error opening stream in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - PvStream::Free(this->lStream); - return ERROR; - } + // this->lResult = lDevice->GetUniqueID(aID); + + // Open stream + //this->lResult = this->lStream->Open( this->ipAddress); //SDK 3 + this->lStream = NULL; + + //this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); //20160309 SDK4 + this->lStream = PvStream::CreateAndOpen(this->ipAddress, &this->lResult); //20160309 SDK4 + + //if ( ( this->lStream == NULL ) || !this->lResult.IsOK() ) + if ( this->lStream == NULL ) + { + printLastError("Error opening stream in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + PvStream::Free( this->lStream ); + return ERROR; + } - // Use min of BUFFER_COUNT and how many buffers can be queued in PvStream - uint32_t lBufferCount = (lStream->GetQueuedBufferMaximum() < BUFFER_COUNT) ? lStream->GetQueuedBufferMaximum() : BUFFER_COUNT; - //new 17-10-2016 for SDK4 - // If this is a GigE Vision device, configure GigE Vision specific streaming parameters - PvStreamGEV *lStreamGEV = static_cast(this->lStream); + // Use min of BUFFER_COUNT and how many buffers can be queued in PvStream + uint32_t lBufferCount = ( lStream->GetQueuedBufferMaximum() < BUFFER_COUNT ) ? + lStream->GetQueuedBufferMaximum() : + BUFFER_COUNT; - if (this->lStream->IsOpen()) - { - //printf("lStream OPEN Local Port %d \n", lStream->GetLocalPort() ); //SDK 3 - printf("lStream OPEN Local Port %u \n", lStreamGEV->GetLocalPort()); //SDK 4 not working.... segmentation fault to check! - } - else - { - printf("lStream NOT OPEN\n"); - } - if (lDevice->IsConnected()) - { - printf("PvDevice connect \n"); - } - else - { - printf("PvDevice not connect \n"); - } + //new 17-10-2016 for SDK4 + // If this is a GigE Vision device, configure GigE Vision specific streaming parameters + PvStreamGEV *lStreamGEV = static_cast( this->lStream ); + + if( this->lStream->IsOpen() ) + { + //printf("lStream OPEN Local Port %d \n", lStream->GetLocalPort() ); //SDK 3 + printf("lStream OPEN Local Port %u \n", lStreamGEV->GetLocalPort() ); //SDK 4 not working.... segmentation fault to check! + } + else + { + printf("lStream NOT OPEN\n"); + } + if(lDevice->IsConnected()) + {printf( "PvDevice connect \n");} + else + {printf( "PvDevice not connect \n");} + + printf("----------> Buffer count %d lSize %d \n", lBufferCount, lSize); + + // Create, alloc buffers + this->lBuffers = new PvBuffer[ lBufferCount ]; + for ( uint32_t i = 0; i < lBufferCount; i++ ) + { + lResult = lBuffers[ i ].Alloc( static_cast( lSize ) ); + if ( !lResult.IsOK() ) + printf("Error memory buffer allocation %d !!!\n(%s)\n", (i+1) , lResult.GetDescription().GetAscii() ); + } - printf("----------> Buffer count %d lSize %d \n", lBufferCount, lSize); + if( lStream->IsOpen() ) printf("lStream OPEN\n"); + else printf("lStream NOT OPEN\n"); - // Create, alloc buffers - this->lBuffers = new PvBuffer[lBufferCount]; - for (uint32_t i = 0; i < lBufferCount; i++) - { - lResult = lBuffers[i].Alloc(static_cast(lSize)); - if (!lResult.IsOK()) - printf("Error memory buffer allocation %d !!!\n(%s)\n", (i + 1), lResult.GetDescription().GetAscii()); - } + if(lDevice->IsConnected()) + printf( "PvDevice connect \n"); + else + printf( "PvDevice not connect \n"); - if (lStream->IsOpen()) - printf("lStream OPEN\n"); - else - printf("lStream NOT OPEN\n"); + // Have to set the Device IP destination to the Stream + //this->lResult = lDevice->SetStreamDestination( lStream->GetLocalIPAddress(), lStream->GetLocalPort() ); //SDK 3 + this->lResult = lDeviceGEV->SetStreamDestination( lStreamGEV->GetLocalIPAddress(), lStreamGEV->GetLocalPort() ); //SDK 4 - 9 mar 2016 + if ( !this->lResult.IsOK() ) {printLastError("Error setting stream dest. in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - if (lDevice->IsConnected()) - printf("PvDevice connect \n"); - else - printf("PvDevice not connect \n"); + if( lStream->IsOpen() ) printf("lStream OPEN\n"); + else printf("lStream NOT OPEN\n"); - // Have to set the Device IP destination to the Stream - //this->lResult = lDevice->SetStreamDestination( lStream->GetLocalIPAddress(), lStream->GetLocalPort() ); //SDK 3 - this->lResult = lDeviceGEV->SetStreamDestination(lStreamGEV->GetLocalIPAddress(), lStreamGEV->GetLocalPort()); //SDK 4 - 9 mar 2016 - if (!this->lResult.IsOK()) - { - printLastError("Error setting stream dest. in start acquisition!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - - if (lStream->IsOpen()) - printf("lStream OPEN\n"); - else - printf("lStream NOT OPEN\n"); + if(lDevice->IsConnected()) + printf( "PvDevice connect \n"); + else + printf( "PvDevice not connect \n"); - if (lDevice->IsConnected()) - printf("PvDevice connect \n"); - else - printf("PvDevice not connect \n"); - // Queue all buffers in the stream - for (uint32_t i = 0; i < lBufferCount; i++) - { - printf("------------------------ Queuing Buffer -----------------------------------\n"); - lResult = lStream->QueueBuffer(&lBuffers[i]); - printf("------------------------ Queued Buffer -----------------------------------\n"); - if (!lResult.IsPending()) - printf("Error buffer enqueue %d !!!\n(%s, %s)\n", (i + 1), lResult.GetDescription().GetAscii(), lResult.GetCodeString().GetAscii()); - } - - if (lStream->IsOpen()) - printf("lStream OPEN\n"); - else - printf("lStream NOT OPEN\n"); + // Queue all buffers in the stream + for ( uint32_t i = 0; i < lBufferCount; i++ ) + { +printf("------------------------ Queuing Buffer -----------------------------------\n"); + lResult = lStream->QueueBuffer( &lBuffers[i] ); +printf("------------------------ Queued Buffer -----------------------------------\n"); + if ( !lResult.IsPending() ) + printf("Error buffer enqueue %d !!!\n(%s, %s)\n", (i+1) , lResult.GetDescription().GetAscii(), lResult.GetCodeString().GetAscii() ); + } - if (lDevice->IsConnected()) - printf("PvDevice connect \n"); - else - printf("PvDevice not connect \n"); + if( lStream->IsOpen() ) printf("lStream OPEN\n"); + else printf("lStream NOT OPEN\n"); - // TLParamsLocked is optional but when present, it MUST be set to 1 - // before sending the AcquisitionStart command - if (lTLLocked != NULL) - { - usleep(3000); - this->lResult = lTLLocked->SetValue(1); + if(lDevice->IsConnected()) + printf( "PvDevice connect \n"); + else + printf( "PvDevice not connect \n"); - if (!this->lResult.IsOK()) + // TLParamsLocked is optional but when present, it MUST be set to 1 + // before sending the AcquisitionStart command + if ( lTLLocked != NULL ) { - printLastError("Error setting TLParamsLocked to 1!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } - } - //reset timestamp counter - printf("2019-09-17: CODE COMMENTED FOR POINT GRAY TESTS \n"); - //2019-09-17 fede comment out for test with point gray visible camera - // this->lResult = lResetTimestamp->Execute(); - // if ( !this->lResult.IsOK() ) {printLastError("Error resetting timestamp counter!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - // Tell the device to start sending images - this->lResult = lStart->Execute(); - if (!this->lResult.IsOK()) - { - printLastError("Error sending StartAcquisition command to device!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } +usleep(3000); + this->lResult = lTLLocked->SetValue( 1 ); - //debug - triggered = 0; - /* + if ( !this->lResult.IsOK() ) {printLastError("Error setting TLParamsLocked to 1!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + } + //reset timestamp counter +printf( "2019-09-17: CODE COMMENTED FOR POINT GRAY TESTS \n"); +//2019-09-17 fede comment out for test with point gray visible camera +// this->lResult = lResetTimestamp->Execute(); +// if ( !this->lResult.IsOK() ) {printLastError("Error resetting timestamp counter!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + // Tell the device to start sending images + this->lResult = lStart->Execute(); + if ( !this->lResult.IsOK() ) {printLastError("Error sending StartAcquisition command to device!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} + +//debug + triggered = 0; +/* printf( "Get Local IP Address %s \n", lStream->GetLocalIPAddress().GetAscii() ); printf( "QueuedBuffer %d \n", lStream->GetQueuedBufferCount() ); printf( "QueuedBuffer Maximum %d \n", lStream->GetQueuedBufferMaximum() ); @@ -986,119 +944,114 @@ end new else printf( "PvStream not open \n"); */ - return SUCCESS; + return SUCCESS; } + + int PTGREY::stopAcquisition() { - PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); - PvGenInteger *lTLLocked = dynamic_cast(lDeviceParams->Get("TLParamsLocked")); - PvGenCommand *lStop = dynamic_cast(lDeviceParams->Get("AcquisitionStop")); + PvGenParameterArray *lDeviceParams = lDevice->GetParameters(); + PvGenInteger *lTLLocked = dynamic_cast( lDeviceParams->Get( "TLParamsLocked" ) ); + PvGenCommand *lStop = dynamic_cast( lDeviceParams->Get( "AcquisitionStop" ) ); - printf("PTGREY : device stop acquisition"); + printf("PTGREY : device stop acquisition"); - // Tell the device to stop sending images - this->lResult = lStop->Execute(); - for (int i = 0; i < 3 && !this->lResult.IsOK(); i++) - { - usleep(30000); + // Tell the device to stop sending images this->lResult = lStop->Execute(); - if (!this->lResult.IsOK()) + for(int i = 0; i < 3 && !this->lResult.IsOK(); i++) { - printf(RED "Try %d : Error sending AcquisitionStop command to the device!!!\n(%s)\n" RESET, i, lResult.GetDescription().GetAscii()); + usleep(30000); + this->lResult = lStop->Execute(); + if ( !this->lResult.IsOK() ) {printf( RED "Try %d : Error sending AcquisitionStop command to the device!!!\n(%s)\n" RESET , i, lResult.GetDescription().GetAscii() ); } } - } - if (!this->lResult.IsOK()) - { - printLastError("Error sending AcquisitionStop command to the device!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; - } + if ( !this->lResult.IsOK() ) {printLastError("Error sending AcquisitionStop command to the device!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} - // If present reset TLParamsLocked to 0. Must be done AFTER the - // streaming has been stopped - if (lTLLocked != NULL) - { - this->lResult = lTLLocked->SetValue(0); - if (!this->lResult.IsOK()) + // If present reset TLParamsLocked to 0. Must be done AFTER the + // streaming has been stopped + if ( lTLLocked != NULL ) { - printLastError("Error resetting TLParamsLocked to 0!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - return ERROR; + this->lResult = lTLLocked->SetValue( 0 ); + if ( !this->lResult.IsOK() ) {printLastError("Error resetting TLParamsLocked to 0!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); return ERROR;} } - } - //printf( "Aborting buffers still in stream\n" ); - lStream->AbortQueuedBuffers(); - while (lStream->GetQueuedBufferCount() > 0) - { - PvBuffer *lBuffer = NULL; - PvResult lOperationResult; - lStream->RetrieveBuffer(&lBuffer, &lOperationResult); - //printf( " Post-abort retrieved buffer: %s\n", lOperationResult.GetCodeString().GetAscii() ); - } + //printf( "Aborting buffers still in stream\n" ); + lStream->AbortQueuedBuffers(); + while ( lStream->GetQueuedBufferCount() > 0 ) + { + PvBuffer *lBuffer = NULL; + PvResult lOperationResult; + lStream->RetrieveBuffer( &lBuffer, &lOperationResult ); + //printf( " Post-abort retrieved buffer: %s\n", lOperationResult.GetCodeString().GetAscii() ); + } - //printf( "Releasing buffers\n" ); - delete[] lBuffers; + //printf( "Releasing buffers\n" ); + delete []lBuffers; - // Now close the stream. Also optionnal but nice to have - printf("Closing stream\n"); - lStream->Close(); + // Now close the stream. Also optionnal but nice to have + printf( "Closing stream\n" ); + lStream->Close(); - return SUCCESS; + + return SUCCESS; } + int PTGREY::getFrame(int *status, void *frame, void *metaData) { - //status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete - // char lDoodle[] = "|\\-|-/"; - // static int lDoodleIndex = 0; - int64_t lImageCountVal = 0; - double lFrameRateVal = 0.0; - double lBandwidthVal = 0.0; - - PvBuffer *lBuffer = NULL; - PvResult lOperationResult; - - // Get stream parameters/stats - PvGenParameterArray *lStreamParams = lStream->GetParameters(); - PvGenInteger *lCount = dynamic_cast(lStreamParams->Get("ImagesCount")); - PvGenFloat *lFrameRate = dynamic_cast(lStreamParams->Get("AcquisitionRateAverage")); - PvGenFloat *lBandwidth = dynamic_cast(lStreamParams->Get("BandwidthAverage")); - - *status = 2; //frame incomplete by default - // ++lDoodleIndex %= 6; - - // Retrieve next buffer - //this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, 1000 ); - int timeOut = int(1. / this->frameRate * 1000.) + 100; - this->lResult = lStream->RetrieveBuffer(&lBuffer, &lOperationResult, timeOut); //Set timeOut to the frame period plus 100ms - - //this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult); - if (this->lResult.IsOK()) - { - if (lOperationResult.IsOK()) +//status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete + // char lDoodle[] = "|\\-|-/"; + // static int lDoodleIndex = 0; + int64_t lImageCountVal = 0; + double lFrameRateVal = 0.0; + double lBandwidthVal = 0.0; + + PvBuffer *lBuffer = NULL; + PvResult lOperationResult; + + // Get stream parameters/stats + PvGenParameterArray *lStreamParams = lStream->GetParameters(); + PvGenInteger *lCount = dynamic_cast( lStreamParams->Get( "ImagesCount" ) ); + PvGenFloat *lFrameRate = dynamic_cast( lStreamParams->Get( "AcquisitionRateAverage" ) ); + PvGenFloat *lBandwidth = dynamic_cast( lStreamParams->Get( "BandwidthAverage" ) ); + + *status=2; //frame incomplete by default + // ++lDoodleIndex %= 6; + + // Retrieve next buffer + //this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, 1000 ); + int timeOut = int (1./this->frameRate * 1000.) + 100; + this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, timeOut ); //Set timeOut to the frame period plus 100ms + + + + //this->lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult); + if ( this->lResult.IsOK() ) { - //lCount->GetValue( lImageCountVal ); //comment out 17-10-2016 with SDK4 segmentation fault - lFrameRate->GetValue(lFrameRateVal); - lBandwidth->GetValue(lBandwidthVal); - - // If the buffer contains an image, display width and height - uint32_t lWidth = 0, lHeight = 0; - if (lBuffer->GetPayloadType() == PvPayloadTypeImage) - { - // Get image specific buffer interface - PvImage *lImage = lBuffer->GetImage(); - // Read width, height - lWidth = lImage->GetWidth(); - lHeight = lImage->GetHeight(); - currTime = lBuffer->GetTimestamp(); - - currIdx = lBuffer->GetBlockID(); - //if( triggered && currIdx != lastIdx+1) - //if( triggered) - // printf("deltaTime ms = %f idx %d tick %d\n", ( ((currTime - lastTime) *.1) / tickFreq) * 1000 , currIdx, tickFreq ); - lastTime = currTime; - lastIdx = currIdx; - /* + if(lOperationResult.IsOK()) + { + //lCount->GetValue( lImageCountVal ); //comment out 17-10-2016 with SDK4 segmentation fault + lFrameRate->GetValue( lFrameRateVal ); + lBandwidth->GetValue( lBandwidthVal ); + + // If the buffer contains an image, display width and height + uint32_t lWidth = 0, lHeight = 0; + if ( lBuffer->GetPayloadType() == PvPayloadTypeImage ) + { + // Get image specific buffer interface + PvImage *lImage = lBuffer->GetImage(); + // Read width, height + lWidth = lImage->GetWidth(); + lHeight = lImage->GetHeight(); + currTime = lBuffer->GetTimestamp(); + + currIdx = lBuffer->GetBlockID(); + //if( triggered && currIdx != lastIdx+1) + //if( triggered) + // printf("deltaTime ms = %f idx %d tick %d\n", ( ((currTime - lastTime) *.1) / tickFreq) * 1000 , currIdx, tickFreq ); + lastTime = currTime; + lastIdx = currIdx; +/* printf( "%c Timestamp: %016llX BlockID: %04X W: %i H: %i %.01f FPS %.01f Mb/s\r", lDoodle[ lDoodleIndex ], lBuffer->GetTimestamp(), @@ -1108,371 +1061,411 @@ int PTGREY::getFrame(int *status, void *frame, void *metaData) lFrameRateVal, lBandwidthVal / 1000000.0 ); */ - unsigned int width = lWidth; - unsigned int height = lHeight; - - // PvUInt8* dataPtr = lImage->GetDataPointer(); //NO!!!! - // PvUInt8* dataPtr = lBuffer->GetDataPointer(); //OK for SDK3 - uint8_t *dataPtr = lBuffer->GetDataPointer(); //8 mar 2016 for SDK4 - - //last 3 rows of the frame are metadata - //memcpy( frame , (unsigned char *)dataPtr, width*height ); //20191107 - memcpy(frame, (unsigned char *)dataPtr, width * height * this->Bpp); //20191107 - // memcpy( metaData , (unsigned char *)dataPtr+(width*2*(height-3)), width*2*3 ); - - //printf("metadata size: %d\n", sizeof(BASLERMETADATA)); - PTGREYMETADATA pgMeta; - pgMeta.gain = this->gain; - pgMeta.exposure = this->exposure; - pgMeta.internalTemperature = this->internalTemperature; - pgMeta.timestamp = currTime; - memcpy(metaData, (unsigned char *)&pgMeta, sizeof(PTGREYMETADATA)); - - *status = 1; //complete - } + unsigned int width = lWidth; + unsigned int height = lHeight; + + // PvUInt8* dataPtr = lImage->GetDataPointer(); //NO!!!! + // PvUInt8* dataPtr = lBuffer->GetDataPointer(); //OK for SDK3 + uint8_t* dataPtr = lBuffer->GetDataPointer(); //8 mar 2016 for SDK4 + + //last 3 rows of the frame are metadata + //memcpy( frame , (unsigned char *)dataPtr, width*height ); //20191107 + memcpy( frame , (unsigned char *)dataPtr, width*height*this->Bpp ); //20191107 + // memcpy( metaData , (unsigned char *)dataPtr+(width*2*(height-3)), width*2*3 ); + + + //printf("metadata size: %d\n", sizeof(BASLERMETADATA)); + PTGREYMETADATA pgMeta; + pgMeta.gain=this->gain; + pgMeta.exposure=this->exposure; + pgMeta.internalTemperature=this->internalTemperature; + pgMeta.timestamp=currTime; + memcpy( metaData , (unsigned char *)&pgMeta, sizeof(PTGREYMETADATA)); + + *status=1; //complete + } + } + else //new 28 agosto 2012 + { + *status=2; //incomplete + //printf( "%c Incomplete\r", lDoodle[ lDoodleIndex ] ); + printf("%s %d\n", lOperationResult.GetCodeString().GetAscii(), lBuffer->GetPayloadType() ); + incompleteFrame++; + } + // We have an image - do some processing (...) and VERY IMPORTANT, + // re-queue the buffer in the stream object + lStream->QueueBuffer( lBuffer ); + return SUCCESS; } - else //new 28 agosto 2012 - { - *status = 2; //incomplete - //printf( "%c Incomplete\r", lDoodle[ lDoodleIndex ] ); - printf("%s %d\n", lOperationResult.GetCodeString().GetAscii(), lBuffer->GetPayloadType()); - incompleteFrame++; + else// Timeout + { + printf("%s (%s) \n", lResult.GetCodeString().GetAscii(), lResult.GetDescription().GetAscii() ); + printLastError("Error reading frame!!!\n(%s)\n", lResult.GetDescription().GetAscii() ); + *status=3; //timeout +// printf( "%c Timeout\r", lDoodle[ lDoodleIndex ] ); + return ERROR; } - // We have an image - do some processing (...) and VERY IMPORTANT, - // re-queue the buffer in the stream object - lStream->QueueBuffer(lBuffer); - return SUCCESS; - } - else // Timeout - { - printf("%s (%s) \n", lResult.GetCodeString().GetAscii(), lResult.GetDescription().GetAscii()); - printLastError("Error reading frame!!!\n(%s)\n", lResult.GetDescription().GetAscii()); - *status = 3; //timeout - // printf( "%c Timeout\r", lDoodle[ lDoodleIndex ] ); - return ERROR; - } -} -int PTGREY::setStreamingMode(int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) -{ - this->streamingEnabled = streamingEnabled; - - if (streamingEnabled) - { - memcpy(this->streamingServer, streamingServer, strlen(streamingServer) + 1); - memcpy(this->deviceName, deviceName, strlen(deviceName) + 1); - this->streamingPort = streamingPort; - this->autoAdjustLimit = autoAdjustLimit; - - this->lowLim = lowLim; - this->highLim = highLim; +} - this->adjRoiX = adjRoiX; - this->adjRoiY = adjRoiY; - this->adjRoiW = adjRoiW; - this->adjRoiH = adjRoiH; - this->minLim = 0; - this->maxLim = 4096; //max value for 12bit resolution of BASLER - } - else - { - printf("Streaming DISABLED\n"); - } - return SUCCESS; -} -int PTGREY::setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber) +int PTGREY::setStreamingMode( int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName) +{ + this->streamingEnabled = streamingEnabled; + + if( streamingEnabled ) + { + memcpy( this->streamingServer, streamingServer, strlen(streamingServer)+1 ); + memcpy( this->deviceName, deviceName, strlen(deviceName)+1 ); + this->streamingPort = streamingPort; + this->autoAdjustLimit = autoAdjustLimit; + + this->lowLim = lowLim; + this->highLim = highLim; + + this->adjRoiX = adjRoiX; + this->adjRoiY = adjRoiY; + this->adjRoiW = adjRoiW; + this->adjRoiH = adjRoiH; + + this->minLim= 0; + this->maxLim= 4096; //max value for 12bit resolution of BASLER + } + else + { + printf("Streaming DISABLED\n"); + } + return SUCCESS; +} + + +int PTGREY::setAcquisitionMode( int storeEnabled , int acqSkipFrameNumber) { - this->storeEnabled = storeEnabled; - this->acqSkipFrameNumber = acqSkipFrameNumber; - return SUCCESS; + this->storeEnabled = storeEnabled; + this->acqSkipFrameNumber = acqSkipFrameNumber; + return SUCCESS; } -int PTGREY::setTriggerMode(int triggerMode, double burstDuration, int numTrigger) +int PTGREY::setTriggerMode( int triggerMode, double burstDuration, int numTrigger ) { - this->triggerMode = triggerMode; - this->burstDuration = burstDuration; - this->numTrigger = numTrigger; + this->triggerMode = triggerMode; + this->burstDuration = burstDuration; + this->numTrigger = numTrigger; - return SUCCESS; + return SUCCESS; } int PTGREY::softwareTrigger() { - this->startStoreTrg = 1; - return SUCCESS; + this->startStoreTrg = 1; + return SUCCESS; } -int PTGREY::setTreeInfo(void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) +int PTGREY::setTreeInfo( void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid) { - this->treePtr = treePtr; - this->framesNid = framesNid; - this->timebaseNid = timebaseNid; - this->framesMetadNid = framesMetadNid; - this->frame0TimeNid = frame0TimeNid; + this->treePtr = treePtr ; + this->framesNid = framesNid; + this->timebaseNid = timebaseNid; + this->framesMetadNid = framesMetadNid; + this->frame0TimeNid = frame0TimeNid; - return SUCCESS; + return SUCCESS; } + void PTGREY::printLastError(const char *format, const char *msg) { - error[0] = 0; - if (msg) - sprintf(error, format, msg); - else - sprintf(error, format); + error[0] = 0; + if(msg) + sprintf(error, format, msg ); + else + sprintf(error, format); } + void PTGREY::getLastError(char *msg) { - sprintf(msg, RED "%s" RESET, (error[0] == 0) ? "" : error); + sprintf(msg, RED "%s" RESET, (error[0]==0) ? "" : error); } int PTGREY::stopFramesAcquisition() { - int count = 0; - - if (acqFlag == 0) - return SUCCESS; - - acqFlag = 0; - while (!acqStopped & count < 20) - { - count++; - usleep(50000); //20190829 FM: 5000->50000 - } - - if (count == 20) - { - printLastError("Cannot stop acquisition loop", 0); - return ERROR; - } - - return SUCCESS; + int count = 0; + + if (acqFlag == 0) + return SUCCESS; + + acqFlag = 0; + while( !acqStopped && count < 20 ) + { + count++; + usleep(50000); //20190829 FM: 5000->50000 + } + + if(count == 20) + { + printLastError("Cannot stop acquisition loop", 0); + return ERROR; + } + + + return SUCCESS; } int PTGREY::startFramesAcquisition() { - int frameTriggerCounter; - int frameCounter; - int frameStatus; - - int NtriggerCount = 0; - int burstNframe; - int rstatus; - int tcpStreamHandle = -1; - - int metaSize; - int savedFrameNumber; - float frameTime = 0.0; - float timeOffset = 0.0; //20200901 - void *saveList; - void *streamingList; - - // short *frameBuffer; //20191107 - // short *metaData; - - void *frameBuffer; - unsigned char *metaData; - unsigned char *frame8bit; - - struct timeval tv; //manage frame timestamp in internal mode - int64_t timeStamp; - int64_t timeStamp0; - - TreeNode *t0Node; - try - { - t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); - Data *nodeData = t0Node->getData(); - timeStamp0 = (int64_t)nodeData->getLong(); - } - catch (const MdsException &exc) - { - printf("Error getting frame0 time\n"); - } - - if (triggerMode != 1) //20200901: in internal mode use the timebaseNid as T0 offset (ex. T_START_SPIDER) - { - TreeNode *tStartOffset; - try - { - tStartOffset = new TreeNode(timebaseNid, (Tree *)treePtr); - Data *nodeData = tStartOffset->getData(); - timeOffset = (float)nodeData->getFloatArray()[0]; - } - catch (const MdsException &exc) - { - printf("Error getting timebaseNid (offset time set to 0.0s)\n"); - timeOffset = 0.0; - } - } - - if (this->Bpp == 1) - { - frameBuffer = (char *)calloc(1, width * height * sizeof(char)); - } - if (this->Bpp == 2) - { - frameBuffer = (short *)calloc(1, width * height * sizeof(short)); - } - frame8bit = (unsigned char *)calloc(1, width * height * sizeof(char)); - - metaSize = sizeof(PTGREYMETADATA); - metaData = (unsigned char *)calloc(1, metaSize); - - camStartSave(&saveList); // # Initialize save frame Linked list reference - - camStartStreaming(&streamingList); // # Initialize streaming frame Linked list reference - - burstNframe = (int)(burstDuration * frameRate + 1); - - acqFlag = 1; - frameTriggerCounter = 0; - frameCounter = 0; - incompleteFrame = 0; - savedFrameNumber = 0; - - startStoreTrg = 0; //manage the mdsplus saving process. SAVE always start with a SW or HW trigger. (0=no-save; 1=save) - - acqStopped = 0; //CT 2021 02 04 - - while (acqFlag) - { - getFrame(&frameStatus, frameBuffer, metaData); //get the frame + int frameTriggerCounter; + int frameCounter; + int frameStatus; + + int NtriggerCount = 0; + int burstNframe; + int rstatus; + int tcpStreamHandle = -1; + + int metaSize; + int savedFrameNumber; + float frameTime = 0.0; + float timeOffset = 0.0; //20200901 + void *saveList; + void *streamingList; + +// short *frameBuffer; //20191107 +// short *metaData; + + void *frameBuffer; + unsigned char *metaData; + unsigned char *frame8bit; + + struct timeval tv; //manage frame timestamp in internal mode + int64_t timeStamp; + int64_t timeStamp0; + + TreeNode *t0Node; + try{ + t0Node = new TreeNode(frame0TimeNid, (Tree *)treePtr); + Data *nodeData = t0Node->getData(); + timeStamp0 = (int64_t)nodeData->getLong(); + }catch(MdsException *exc) + { + printf("Error getting frame0 time\n"); + } + + + //if ( triggerMode != 1 ) //20200901: in internal mode use the timebaseNid as T0 offset (ex. T_START_SPIDER) + { //20210325: In external trigger, triggered on event must be set timeOffest + TreeNode *tStartOffset; + try{ + tStartOffset = new TreeNode(timebaseNid, (Tree *)treePtr); + Data *nodeData = tStartOffset->getData(); + timeOffset = (float)nodeData->getFloatArray()[0]; + }catch(MdsException *exc) + { + printf("Error getting timebaseNid (offset time set to 0.0s)\n"); + timeOffset=0.0; + } + } - if (storeEnabled) - { - if (triggerMode == 1) // External trigger source - { - if ((frameStatus == 4 || eventTrigger == 1) && (startStoreTrg == 0)) //start data storing @ 1st trigger seen (trigger is on image header!) - //CT In External Trigger Mode acquisition is also triggered on MDSevent + if(this->Bpp==1) { - startStoreTrg = 1; - eventTrigger = 0; //CT Reset MDSplus trigger event flag - printf("TRIGGERED: %d %d\n", frameStatus, eventTrigger); + frameBuffer = (char *) calloc(1, width * height * sizeof(char)); } - - if (frameTriggerCounter == burstNframe) + if(this->Bpp==2) { - triggered = 0; - startStoreTrg = 0; //disable storing - NtriggerCount++; + frameBuffer = (short *) calloc(1, width * height * sizeof(short)); + } + frame8bit = (unsigned char *) calloc(1, width * height * sizeof(char)); - printf("ACQUIRED ALL FRAMES %d FOR TRIGGER : %d\n", frameTriggerCounter - 1, NtriggerCount); - frameTriggerCounter = 0; + metaSize = sizeof(PTGREYMETADATA); + metaData = (unsigned char *)calloc(1, metaSize); - if (NtriggerCount == numTrigger) //stop store when all trigger will be received - { - printf("ACQUIRED ALL FRAME BURST: %d\n", numTrigger); - storeEnabled = 0; - //break; - } - } //if (frameTriggerCounter == burstNframe) - } - else //( triggerMode == 1 ) //Internal trigger source - { - //Multiple trigger acquisition: first trigger save 64bit timestamp - timebaseNid = -1; //used in cammdsutils to use internal - triggered = 1; //debug - - if (startStoreTrg == 1) - { - gettimeofday(&tv, NULL); - timeStamp = ((tv.tv_sec) * 1000) + ((tv.tv_usec) / 1000); // timeStamp [ms] + camStartSave(&saveList); // # Initialize save frame Linked list reference - if (timeStamp0 == 0) - { - Int64 *tsMDS = new Int64(timeStamp); - t0Node->putData(tsMDS); - timeStamp0 = timeStamp; - } - else - { - frameTime = (float)((timeStamp - timeStamp0) / 1000.0); //interval from first frame [s] - //printf("frameTime: %f", frameTime); - } - } //if startStoreTrg == 1 + camStartStreaming(&streamingList); // # Initialize streaming frame Linked list reference - if (frameTriggerCounter == burstNframe) - { - startStoreTrg = 0; //disable storing - frameTriggerCounter = 0; - NtriggerCount++; - printf("Stop Internal trigger acquisition %f %f %f\n", frameTime, burstDuration, frameRate); - //storeEnabled=0; //infinite trigger until stop acquisition - //break; - } - } //else Internal trigger source - } //if(storeEnabled) + burstNframe = (int) ( burstDuration * frameRate + 1. + 0.5);//CT 2021 03 20 - //frameStatus -> status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete - if ((frameStatus != 3) && (storeEnabled == 1 && startStoreTrg == 1) && (acqSkipFrameNumber <= 0 || (frameTriggerCounter % (acqSkipFrameNumber + 1)) == 0)) - { - int frameTimeBaseIdx; - frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; - - // CT la routine camSaveFrame utilizza il frame index in acquisizione. L'indice viene - // utilizzato per individuare nell'array della base temporale il tempo associato al frame. - - // Con Trigger interno viene utilizzato frameTime come tempo relativo allo 0; timebaseNid deve essere -1 - if (timebaseNid == -1) - printf("DEBUG TO REMOVE 20200904 - FRAME TIME: (%s) %f\n", this->ipAddress.GetAscii(), frameTime + timeOffset); - else - printf("(%s) SAVE Num Tr : %2d Frame Tr. Cnt : %5d timebase Idx : %5d\n", this->ipAddress.GetAscii(), NtriggerCount, frameTriggerCounter, frameTimeBaseIdx); - camSaveFrame((void *)frameBuffer, width, height, frameTime + timeOffset, 8 * this->Bpp, (void *)treePtr, framesNid, timebaseNid, frameTimeBaseIdx, (void *)metaData, metaSize, framesMetadNid, saveList); - savedFrameNumber++; - } + acqFlag = 1; + frameTriggerCounter = 0; + frameCounter = 0; + incompleteFrame = 0; + savedFrameNumber = 0; - if (streamingEnabled) - { - if (tcpStreamHandle == -1) - { - rstatus = camOpenTcpConnection(streamingServer, streamingPort, &tcpStreamHandle, width, height, pixelFormat); - if (rstatus != -1) + startStoreTrg = 0; //manage the mdsplus saving process. SAVE always start with a SW or HW trigger. (0=no-save; 1=save) + + acqStopped = 0;//CT 2021 02 04 + + while ( acqFlag ) + { + getFrame( &frameStatus, frameBuffer, metaData); //get the frame + + if(storeEnabled) { - printf("Connected to FFMPEG on %s : %d\n", streamingServer, streamingPort); - } - else + if ( triggerMode == 1 ) // External trigger source + { + + if ( (frameStatus == 4 || eventTrigger == 1 ) && (startStoreTrg == 0) ) //start data storing @ 1st trigger seen (trigger is on image header!) + //CT In External Trigger Mode acquisition is also triggered on MDSevent + { + startStoreTrg = 1; + + if( eventTrigger == 1 )//For debug in Event trigger mode is disable time base and use local time frame time stamp + { + timebaseNid = -1; + if(NtriggerCount == 0 ) timeStamp0 = 0; + } + + eventTrigger = 0; //CT Reset MDSplus trigger event flag + printf("TRIGGERED: %d %d\n", frameStatus, eventTrigger); + } + + if (frameTriggerCounter == burstNframe) + { + triggered = 0; + startStoreTrg = 0; //disable storing + NtriggerCount++; + + printf("ACQUIRED ALL FRAMES %d FOR TRIGGER : %d\n", frameTriggerCounter-1, NtriggerCount ); + frameTriggerCounter = 0; + + if ( NtriggerCount == numTrigger ) //stop store when all trigger will be received + { + printf("ACQUIRED ALL FRAME BURST: %d\n", numTrigger ); + storeEnabled=0; + //break; + } + }//if (frameTriggerCounter == burstNframe) + + +/* Time stamp for acquisition in Event trigger */ + if(startStoreTrg == 1) + { + gettimeofday(&tv, NULL); + timeStamp = ((tv.tv_sec)*1000) + ((tv.tv_usec)/1000); // timeStamp [ms] + + if(timeStamp0==0) + { + Int64 *tsMDS = new Int64(timeStamp); + t0Node->putData(tsMDS); + timeStamp0=timeStamp; + printf("frameTime stamp 0: %f", timeStamp0); + } + else + { + frameTime = (float)((timeStamp-timeStamp0)/1000.0); //interval from first frame [s] + // printf("frameTime: %f", frameTime); + } + }//if startStoreTrg == 1 + +/*************************/ + + } + else //( triggerMode == 1 ) //Internal trigger source + { + //Multiple trigger acquisition: first trigger save 64bit timestamp + timebaseNid = -1; //used in cammdsutils to use internal + triggered = 1; //debug + + if(startStoreTrg == 1) + { + gettimeofday(&tv, NULL); + timeStamp = ((tv.tv_sec)*1000) + ((tv.tv_usec)/1000); // timeStamp [ms] + + if(timeStamp0==0) + { + Int64 *tsMDS = new Int64(timeStamp); + t0Node->putData(tsMDS); + timeStamp0=timeStamp; + } + else + { + frameTime = (float)((timeStamp-timeStamp0)/1000.0); //interval from first frame [s] + //printf("frameTime: %f", frameTime); + } + }//if startStoreTrg == 1 + + if ( frameTriggerCounter == burstNframe ) + { + startStoreTrg = 0; //disable storing + frameTriggerCounter = 0; + NtriggerCount++; + printf("Stop Internal trigger acquisition %f %f %f\n", frameTime, burstDuration, frameRate); + //storeEnabled=0; //infinite trigger until stop acquisition + //break; + } + }//else Internal trigger source + }//if(storeEnabled) + + + //frameStatus -> status=1 complete # status=2 incomplete # status=3 timeout # status=4 triggered frame + complete + if( (frameStatus != 3 ) && ( storeEnabled == 1 && startStoreTrg == 1 ) && ( acqSkipFrameNumber <= 0 || (frameTriggerCounter % (acqSkipFrameNumber + 1) ) == 0 ) ) + { + int frameTimeBaseIdx; + frameTimeBaseIdx = NtriggerCount * burstNframe + frameTriggerCounter; + + // CT la routine camSaveFrame utilizza il frame index in acquisizione. L'indice viene + // utilizzato per individuare nell'array della base temporale il tempo associato al frame. + + // Con Trigger interno viene utilizzato frameTime come tempo relativo allo 0; timebaseNid deve essere -1 + if (timebaseNid == -1 ) + printf("DEBUG TO REMOVE 20200904 - FRAME TIME: (%s) %f\n", this->ipAddress.GetAscii(), frameTime+timeOffset); + else + printf("(%s) SAVE Num Tr : %2d Frame Tr. Cnt : %5d timebase Idx : %5d\n", this->ipAddress.GetAscii(), NtriggerCount, frameTriggerCounter, frameTimeBaseIdx); + camSaveFrame((void *)frameBuffer, width, height, frameTime+timeOffset, 8*this->Bpp, (void *)treePtr, framesNid, timebaseNid, frameTimeBaseIdx, (void *)metaData, metaSize, framesMetadNid, saveList); + savedFrameNumber++; + } + + if( streamingEnabled ) + { + if( tcpStreamHandle == -1) + { + rstatus = camOpenTcpConnection(streamingServer, streamingPort, &tcpStreamHandle, width, height, pixelFormat); + if( rstatus !=-1 ) + { + printf( "Connected to FFMPEG on %s : %d\n", streamingServer, streamingPort); + } + else + { + printf( "Cannot connect to FFMPEG on %s : %d. Disable streaming\n", streamingServer, streamingPort); + streamingEnabled = 0; + } + } + //if ( (streamingSkipFrameNumber - 1 <= 0) || (frameCounter % ( streamingSkipFrameNumber - 1)) == 0 ) //20170327 - ORIGINAL + else if((this->frameRate<10) || (frameCounter % int(this->frameRate/10.0))==0) //send frame @ 10Hz. Reduce CPU usage when radiometric conversion must be performed. + { + camStreamingFrame( tcpStreamHandle, frameBuffer, width, height, pixelFormat, 0, autoAdjustLimit, &lowLim, &highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, this->deviceName, streamingList); + } + } // if( streamingEnabled ) + + frameCounter++; //never resetted, used for frame timestamp + if ( startStoreTrg == 1 ) //CT incremento l'indice dei frame salvato solo se l'acquisizione e' stata triggerata { - printf("Cannot connect to FFMPEG on %s : %d. Disable streaming\n", streamingServer, streamingPort); - streamingEnabled = 0; + frameTriggerCounter++; } - } - //if ( (streamingSkipFrameNumber - 1 <= 0) || (frameCounter % ( streamingSkipFrameNumber - 1)) == 0 ) //20170327 - ORIGINAL - else if ((this->frameRate < 10) || (frameCounter % int(this->frameRate / 10.0)) == 0) //send frame @ 10Hz. Reduce CPU usage when radiometric conversion must be performed. - { - camStreamingFrame(tcpStreamHandle, frameBuffer, width, height, pixelFormat, 0, autoAdjustLimit, &lowLim, &highLim, minLim, maxLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, this->deviceName, streamingList); - } - } // if( streamingEnabled ) - - frameCounter++; //never resetted, used for frame timestamp - if (startStoreTrg == 1) //CT incremento l'indice dei frame salvato solo se l'acquisizione e' stata triggerata - { - frameTriggerCounter++; - } - } //endwhile + }//endwhile - camStopSave(saveList); // Stop asynhronous store stream - camStopStreaming(streamingList); // Stop asynhronous frame streaming + camStopSave(saveList); // Stop asynhronous store stream + camStopStreaming(streamingList); // Stop asynhronous frame streaming - if (tcpStreamHandle != -1) - camCloseTcpConnection(&tcpStreamHandle); + if( tcpStreamHandle != -1 ) + camCloseTcpConnection(&tcpStreamHandle); - rstatus = stopAcquisition(); //stop camera acquisition - if (rstatus < 0) - printf(RED " Cannot stop camera acquisition \n" RESET); + rstatus = stopAcquisition(); //stop camera acquisition + if (rstatus < 0) + printf(RED " Cannot stop camera acquisition \n" RESET ); - free(frameBuffer); - free(frame8bit); - free(metaData); + + free(frameBuffer); + free(frame8bit); + free(metaData); - printf("Acquisition Statistics : \tTotal frames read %d, \n\t\t\t\tTotal frames stored %d (expected %d), \n\t\t\t\tNumber of trigger %d (expected %d), \n\t\t\t\tIncomplete frame %d\n", frameCounter, savedFrameNumber, numTrigger * (1 + (int)(burstDuration * (frameRate - acqSkipFrameNumber))), NtriggerCount + startStoreTrg, numTrigger, incompleteFrame); + printf("Acquisition Statistics : \tTotal frames read %d, \n\t\t\t\tTotal frames stored %d (expected %d), \n\t\t\t\tNumber of trigger %d (expected %d), \n\t\t\t\tIncomplete frame %d\n", frameCounter, savedFrameNumber, numTrigger * (1+(int)( burstDuration * (frameRate-acqSkipFrameNumber))), NtriggerCount + startStoreTrg, numTrigger, incompleteFrame ); - acqStopped = 1; + acqStopped = 1; - return rstatus; + return rstatus; } + diff --git a/device_support/ptgrey/PTGREY.h b/device_support/ptgrey/PTGREY.h index baedfbb14c..51dae69500 100644 --- a/device_support/ptgrey/PTGREY.h +++ b/device_support/ptgrey/PTGREY.h @@ -5,230 +5,236 @@ #include #include -#include //new 9mar2016 for SDK4 +#include //new 9mar2016 for SDK4 #include -#include //new 9mar2016 for SDK4 +#include //new 9mar2016 for SDK4 using namespace MDSplus; -#define RESET "\033[0m" -#define BLACK "\033[30m" /* Black */ -#define RED "\033[31m" /* Red */ -#define GREEN "\033[32m" /* Green */ -#define YELLOW "\033[33m" /* Yellow */ -#define BLUE "\033[34m" /* Blue */ -#define MAGENTA "\033[35m" /* Magenta */ -#define CYAN "\033[36m" /* Cyan */ -#define WHITE "\033[37m" /* White */ -#define BOLDBLACK "\033[1m\033[30m" /* Bold Black */ -#define BOLDRED "\033[1m\033[31m" /* Bold Red */ -#define BOLDGREEN "\033[1m\033[32m" /* Bold Green */ -#define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ -#define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */ -#define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */ -#define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */ -#define BOLDWHITE "\033[1m\033[37m" /* Bold White */ - -#ifdef __cplusplus -extern "C" -{ -#endif +#define RESET "\033[0m" +#define BLACK "\033[30m" /* Black */ +#define RED "\033[31m" /* Red */ +#define GREEN "\033[32m" /* Green */ +#define YELLOW "\033[33m" /* Yellow */ +#define BLUE "\033[34m" /* Blue */ +#define MAGENTA "\033[35m" /* Magenta */ +#define CYAN "\033[36m" /* Cyan */ +#define WHITE "\033[37m" /* White */ +#define BOLDBLACK "\033[1m\033[30m" /* Bold Black */ +#define BOLDRED "\033[1m\033[31m" /* Bold Red */ +#define BOLDGREEN "\033[1m\033[32m" /* Bold Green */ +#define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ +#define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */ +#define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */ +#define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */ +#define BOLDWHITE "\033[1m\033[37m" /* Bold White */ + + +#ifdef __cplusplus +extern "C" +{ +#endif + +//extern int flirRadiometricConv(void *frame, int width, int height, void *metaData); - //extern int flirRadiometricConv(void *frame, int width, int height, void *metaData); +// Wrapper for Python that must see the cpp class as standard C functions - // Wrapper for Python that must see the cpp class as standard C functions +int PGopen(const char *cameraName, int *camHandle); +int PGclose(int camHandle); +int checkLastOp(int camHandle); +int printAllParameters(int camHandle); +int readInternalTemperature(int camHandle); +int setExposure(int camHandle, float exposure); +int setExposureAuto(int camHandle, char *exposureAuto); +int setGammaEnable(int camHandle, char *gammaEnable); +int setGain(int camHandle, float gain); +int setGainAuto(int camHandle, char *gainAuto); - int PGopen(const char *cameraName, int *camHandle); - int PGclose(int camHandle); - int checkLastOp(int camHandle); - int printAllParameters(int camHandle); - int readInternalTemperature(int camHandle); - int setExposure(int camHandle, float exposure); - int setExposureAuto(int camHandle, char *exposureAuto); - int setGammaEnable(int camHandle, char *gammaEnable); - int setGain(int camHandle, float gain); - int setGainAuto(int camHandle, char *gainAuto); - //int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip); - //int setFrameRateNew(int camHandle, double frameRate); - int setFrameRate(int camHandle, double *frameRate); +//int setFrameRate(int camHandle, FPS_ENUM frameRate, int *frameToSkip); +//int setFrameRateNew(int camHandle, double frameRate); +int setFrameRate(int camHandle, double *frameRate); - //int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height); - int setReadoutArea(int camHandle, int x, int y, int width, int height); +//int getReadoutArea(int camHandle, int *x, int *y, int *width, int *height); +int setReadoutArea(int camHandle, int x, int y, int width, int height); + +int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber ); - int setAcquisitionMode(int camHandle, int storeEnabled, int acqSkipFrameNumber); +int setPixelFormat(int camHandle, char *pixelFormat); - int setPixelFormat(int camHandle, char *pixelFormat); +int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); +int stopAcquisition(int camHandle); +int getFrame(int camHandle, int *status, void *frame, void *metaData); +//int frameConv(int camHandle, unsigned short *frame, int width, int height); +int startFramesAcquisition(int camHandle); +int stopFramesAcquisition(int camHandle); - int startAcquisition(int camHandle, int *width, int *height, int *payloadSize); - int stopAcquisition(int camHandle); - int getFrame(int camHandle, int *status, void *frame, void *metaData); - //int frameConv(int camHandle, unsigned short *frame, int width, int height); - int startFramesAcquisition(int camHandle); - int stopFramesAcquisition(int camHandle); - int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); +int setStreamingMode(int camHandle, int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, int lowLim, int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); - int setTriggerMode(int camHandle, int triggerMode, double burstDuration, int numTrigger); - int softwareTrigger(int camHandle); - int setTreeInfo(int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); +int setTriggerMode(int camHandle, int triggerMode, double burstDuration, int numTrigger ); +int softwareTrigger(int camHandle); +int setTreeInfo( int camHandle, void *treePtr, int framesNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); - void getLastError(int camHandle, char *msg); +void getLastError(int camHandle, char *msg); -#ifdef __cplusplus -} -#endif +#ifdef __cplusplus +} +#endif -typedef struct _ptgreyMetaData + +typedef struct _ptgreyMetaData { - float gain; - float exposure; - float internalTemperature; - int64_t timestamp; -} PTGREYMETADATA; + float gain; + float exposure; + float internalTemperature; + int64_t timestamp; +}PTGREYMETADATA; + class PTGREY { - class TriggerMdsEvent : public Event - { - private: - PTGREY *ptGray; - - public: - TriggerMdsEvent(const char *name, PTGREY *ptGr) : Event(name) - { - ptGray = ptGr; - } - - void run() - { - size_t bufSize; - const char *name = getName(); //Get the name of the event - char *date = getTime()->getDate(); //Get the event reception date in string format - const char *buf = getRaw(&bufSize); //Get raw data - char *str = new char[bufSize + 1]; //Make it a string - memcpy(str, buf, bufSize); - str[bufSize] = 0; - //MDSevent trigger is set if camera is in acquisition, Frame store is enabled and camera is not saving frame. - //An event trigger received during acquisition can reset the trigger count to extend the acquisition - if (ptGray->acqFlag && ptGray->storeEnabled && ptGray->startStoreTrg == 0) - { - printf("%s EVENT Trigger Start!!!!\n", (ptGray->ipAddress).GetAscii()); - ptGray->eventTrigger = 1; - } - else - { - printf("%s EVENT Trigger Reset!!!!\n", (ptGray->ipAddress).GetAscii()); - ptGray->eventTrigger = 0; - } - printf("%s RECEIVED EVENT %s AT %s WITH DATA %s Event Trig %d (%d,%d,%d)\n", (ptGray->ipAddress).GetAscii(), name, date, str, ptGray->eventTrigger); - delete str; - } - }; - -private: - PvDevice *lDevice; //camera handle - PvStream *lStream; //stream handle - PvBuffer *lBuffers; //buffer handle - PvResult lResult; //result of the latest operation - PvString ipAddress; //camera ip address - TriggerMdsEvent *trigEvent; - - int x; - int y; - int width; - int height; - int pixelFormat; //all pixelFormat supported are in camstreamutils.h - int Bpp; //Bytes per pixel - double frameRate; - float gain; - float exposure; - float internalTemperature; - - int storeEnabled; - int triggerMode; - int startStoreTrg; - int autoCalibration; - int irFrameFormat; - int eventTrigger; //CT on MDSplus event trigger flag - - int streamingEnabled; - int streamingSkipFrameNumber; - char streamingServer[512]; - int streamingPort; - int autoScale; - unsigned int lowLim; - unsigned int highLim; - unsigned int minLim; - unsigned int maxLim; - bool autoAdjustLimit; - int adjRoiX; - int adjRoiY; - int adjRoiW; - int adjRoiH; - char deviceName[64]; - - int imageMode; - int acqSkipFrameNumber; - double burstDuration; - int numTrigger; - - void *treePtr; - int framesNid; - int timebaseNid; - int framesMetadNid; - int frame0TimeNid; - - int acqFlag; - int acqStopped; - char error[512]; - int incompleteFrame; - - //debug - uint64_t currTime, lastTime, currIdx, lastIdx, triggered; - int64_t tickFreq; - -public: - //camera - PTGREY(const char *ipAddress); - PTGREY(); //new 23 July 2013 for test purposes - ~PTGREY(); - - //info - int checkLastOp(); - int printAllParameters(); - - //settings - int readInternalTemperature(); - int setExposure(float exposure); - int setExposureAuto(char *exposureAuto); - int setGain(float gain); - int setGainAuto(char *gainAuto); - int setGammaEnable(char *gammaEnable); - int setFrameRate(double &frameRate); - // int setFrameRate(FPS_ENUM fps, int *frameToSkip); - // int getReadoutArea(int *x, int *y, int *width, int *height); - int setReadoutArea(int x, int y, int width, int height); - int setPixelFormat(char *pixelFormat); - - int setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber); - int setStreamingMode(int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); - - int setTriggerMode(int triggerMode, double burstDuration, int numTrigger); - int setTreeInfo(void *treePtr, int frameNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); - - void getLastError(char *msg); - void printLastError(const char *format, const char *msg); - - //acquisition - int startAcquisition(int *width, int *height, int *payloadSize); - int stopAcquisition(); - int softwareTrigger(); - int getFrame(int *status, void *frame, void *metaData); + class TriggerMdsEvent:public Event + { + private: + PTGREY* ptGray; + public: + TriggerMdsEvent(const char *name, PTGREY* ptGr):Event(name) + { + ptGray = ptGr; + } + + void run() + { + size_t bufSize; + const char *name = getName(); //Get the name of the event + char *date = getTime()->getDate(); //Get the event reception date in string format + const char *buf = getRaw(&bufSize); //Get raw data + char *str = new char[bufSize+1]; //Make it a string + memcpy(str, buf, bufSize); + str[bufSize] = 0; + //MDSevent trigger is set if camera is in acquisition, Frame store is enabled and camera is not saving frame. + //An event trigger received during acquisition can reset the trigger count to extend the acquisition + if(ptGray->acqFlag && ptGray->storeEnabled && ptGray->startStoreTrg == 0) + { + printf("%s EVENT Trigger Start!!!!\n", (ptGray->ipAddress).GetAscii()); + ptGray->eventTrigger = 1; + } else { + printf("%s EVENT Trigger Reset!!!!\n", (ptGray->ipAddress).GetAscii()); + ptGray->eventTrigger = 0; + } + printf("%s RECEIVED EVENT %s AT %s WITH DATA %s Event Trig %d (%d,%d,%d)\n",(ptGray->ipAddress).GetAscii() ,name, date, str, ptGray->eventTrigger); + delete str; + } + }; + + private: + PvDevice *lDevice; //camera handle + PvStream *lStream; //stream handle + PvBuffer *lBuffers; //buffer handle + PvResult lResult; //result of the latest operation + PvString ipAddress; //camera ip address + TriggerMdsEvent *trigEvent; + + int x; + int y; + int width; + int height; + int pixelFormat; //all pixelFormat supported are in camstreamutils.h + int Bpp; //Bytes per pixel + double frameRate; + float gain; + float exposure; + float internalTemperature; + + int storeEnabled; + int triggerMode; + int startStoreTrg; + int autoCalibration; + int irFrameFormat; + int eventTrigger; //CT on MDSplus event trigger flag + + + int streamingEnabled; + int streamingSkipFrameNumber; + char streamingServer[512]; + int streamingPort; + int autoScale; + unsigned int lowLim; + unsigned int highLim; + unsigned int minLim; + unsigned int maxLim; + bool autoAdjustLimit; + int adjRoiX; + int adjRoiY; + int adjRoiW; + int adjRoiH; + char deviceName[64]; + + int imageMode; + int acqSkipFrameNumber; + double burstDuration; + int numTrigger; + + void* treePtr; + int framesNid; + int timebaseNid; + int framesMetadNid; + int frame0TimeNid; + + int acqFlag; + int acqStopped; + char error[512]; + int incompleteFrame; + + //debug + uint64_t currTime, lastTime, currIdx, lastIdx, triggered; + int64_t tickFreq; + + + public: + //camera + PTGREY(const char *ipAddress); + PTGREY(); //new 23 July 2013 for test purposes + ~PTGREY(); + + //info + int checkLastOp(); + int printAllParameters(); + + //settings + int readInternalTemperature(); + int setExposure(float exposure); + int setExposureAuto(char *exposureAuto); + int setGain(float gain); + int setGainAuto(char *gainAuto); + int setGammaEnable(char *gammaEnable); + int setFrameRate(double &frameRate); +// int setFrameRate(FPS_ENUM fps, int *frameToSkip); +// int getReadoutArea(int *x, int *y, int *width, int *height); + int setReadoutArea(int x, int y, int width, int height); + int setPixelFormat(char *pixelFormat); + + int setAcquisitionMode(int storeEnabled, int acqSkipFrameNumber); + int setStreamingMode( int streamingEnabled, bool autoAdjustLimit, const char *streamingServer, int streamingPort, unsigned int lowLim, unsigned int highLim, int adjRoiX, int adjRoiY, int adjRoiW, int adjRoiH, const char *deviceName); + + int setTriggerMode( int triggerMode, double burstDuration, int numTrigger ); + int setTreeInfo( void *treePtr, int frameNid, int timebaseNid, int framesMetadNid, int frame0TimeNid); + + void getLastError(char *msg); + void printLastError(const char *format, const char *msg); + + //acquisition + int startAcquisition(int *width, int *height, int *payloadSize); + int stopAcquisition(); + int softwareTrigger(); + int getFrame(int *status, void *frame, void *metaData); // int frameConv(unsigned short *frame, int width, int height); - int startFramesAcquisition(); - int stopFramesAcquisition(); + int startFramesAcquisition(); + int stopFramesAcquisition(); + + + protected: -protected: }; diff --git a/examples/demoadc/DemoAdc.c b/examples/demoadc/DemoAdc.c index 2b37aa97fb..87fe11feb0 100644 --- a/examples/demoadc/DemoAdc.c +++ b/examples/demoadc/DemoAdc.c @@ -49,6 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include +#include #define PI 3.14159265358 static int totSamples = 65536; static double frequency; @@ -91,6 +92,7 @@ int initialize(char *name, int clockFreq, int postTriggerSamples) int acquire(char *name, short *c1, short *c2, short *c3, short *c4) { int i; + printf("ACQUIRE\n"); // it is assumed that c1,c2,c3,c4 arrays have totSamples elements if (!confOk) return -1; @@ -103,3 +105,34 @@ int acquire(char *name, short *c1, short *c2, short *c3, short *c4) } return 0; } + +static long currSamples; +static double currPeriod; +static double trigger; +int initializeStream(char *name, float clockFreq, float trigTime) +{ + printf("INITIALIZE STREAM: %s, %f, %f\n", name, clockFreq, trigTime); + currPeriod = 1./clockFreq; + trigger = trigTime; + currSamples = 0; + return 0; +} + +int acquireChunk(char *name, short *chunk, int numSamples) +{ + int i; + double currTime; + struct timespec waitTime; + waitTime.tv_sec = 0; + waitTime.tv_nsec = 500000000; + for(i = 0; i < numSamples; i++) + { + currTime = trigger + currSamples * currPeriod; + chunk[i] = (short)(sin(2 * PI * currTime) * 32767); + currSamples++; + } + nanosleep(&waitTime, NULL); + + return 0; +} + diff --git a/java/devicebeans/src/main/java/DeviceInputs.java b/java/devicebeans/src/main/java/DeviceInputs.java index 440811fbb9..0ca648b8ad 100644 --- a/java/devicebeans/src/main/java/DeviceInputs.java +++ b/java/devicebeans/src/main/java/DeviceInputs.java @@ -13,7 +13,7 @@ public class DeviceInputs extends DeviceComponent private JScrollPane scrollP; private int numInputs; - private JTextField valuesTF[], fieldsTF[][]; + private JTextField valuesTF[], fieldsTF[][], parametersTF[][]; private JLabel labels[]; int numParameters[], numFields[]; public DeviceInputs() @@ -37,6 +37,7 @@ protected void initializeData(String data, boolean is_on) fieldsTF = new JTextField[numInputs][]; numParameters = new int[numInputs]; numFields = new int[numInputs]; + parametersTF = new JTextField[numInputs][]; JPanel jp = new JPanel(); jp.setLayout(new GridLayout(numInputs, 1)); int currInputNid = currNid + 1; @@ -69,6 +70,7 @@ protected void initializeData(String data, boolean is_on) } } fieldsTF[i] = new JTextField[numFields[i]]; + parametersTF[i] = new JTextField[numParameters[i]]; String inputName; try { inputName = subtree.getString(subtree.getDataExpr(currInputNid + 5)); @@ -78,19 +80,32 @@ protected void initializeData(String data, boolean is_on) } JPanel jp1 = new JPanel(); TitledBorder titledBorder = new TitledBorder(inputName); - titledBorder.setTitleColor(Color.red); + //titledBorder.setTitleColor(Color.red); jp1.setBorder(titledBorder); jp1.setLayout(new GridLayout(1 + numFields[i],1)); JPanel jp2 = new JPanel(); - jp2.setLayout(new BorderLayout()); - jp2.add(valuesTF[i] = new JTextField(), "Center"); + // jp2.setLayout(new BorderLayout()); + //jp2.add(valuesTF[i] = new JTextField(), "Center"); + jp2.add(valuesTF[i] = new JTextField(30)); + for(int parIdx = 0; parIdx < numParameters[i]; parIdx++) + { + java.lang.String parName = ""; + try { + parName = subtree.getString(subtree.getDataExpr(currInputNid + 8 + 3 * parIdx)); + }catch(Exception exc) + { + System.out.println("Cannot read parameter name"); + } + jp2.add(new JLabel(parName+":")); + jp2.add(parametersTF[i][parIdx] = new JTextField(10)); + } jp1.add(jp2); for (int fieldIdx = 0; fieldIdx < numFields[i]; fieldIdx++) { String fieldName; try { - fieldName = subtree.getString(subtree.getDataExpr(currInputNid + 8 + 2 * numParameters[i] + 6 * fieldIdx + 4)); + fieldName = subtree.getString(subtree.getDataExpr(currInputNid + 8 + 3 * numParameters[i] + 6 * fieldIdx + 4)); }catch(Exception exc) { fieldName = ""; @@ -101,7 +116,7 @@ protected void initializeData(String data, boolean is_on) jp2.add(fieldsTF[i][fieldIdx] = new JTextField(), "Center"); jp1.add(jp2); } - currInputNid += numInputChildren + 1 + 2 * numParameters[i] + 6 * numFields[i]; + currInputNid += numInputChildren + 1 + 3 * numParameters[i] + 6 * numFields[i]; jp.add(jp1); } scrollP = new JScrollPane(jp); @@ -129,13 +144,22 @@ protected void displayData(String data, boolean is_on) { valuesTF[inputIdx].setText(""); } + for(int parIdx = 0; parIdx < numParameters[inputIdx]; parIdx++) + { + try { + parametersTF[inputIdx][parIdx].setText(subtree.getDataExpr(currInputNid + 9 + 3 * parIdx)); + }catch(Exception exc) + { + parametersTF[inputIdx][parIdx].setText(""); + } + } for(int fieldIdx = 0; fieldIdx < numFields[inputIdx]; fieldIdx++) { try { - fieldsTF[inputIdx][fieldIdx].setText(subtree.getDataExpr(currInputNid + 8 + 2 * numParameters[inputIdx] + 6 * fieldIdx + 5)); + fieldsTF[inputIdx][fieldIdx].setText(subtree.getDataExpr(currInputNid + 8 + 3 * numParameters[inputIdx] + 6 * fieldIdx + 5)); }catch(Exception exc){fieldsTF[inputIdx][fieldIdx].setText("");} } - currInputNid += numInputChildren + 1 + 2 * numParameters[inputIdx] + 6 * numFields[inputIdx]; + currInputNid += numInputChildren + 1 + 3 * numParameters[inputIdx] + 6 * numFields[inputIdx]; } } @@ -162,17 +186,26 @@ public void apply() throws Exception { JOptionPane.showMessageDialog(null, ""+exc, "Error in input field "+inputIdx, JOptionPane.WARNING_MESSAGE); } + for(int parIdx = 0; parIdx < numParameters[inputIdx]; parIdx++) + { + try { + subtree.putDataExpr(currInputNid + 9 + 3 * parIdx, parametersTF[inputIdx][parIdx].getText()); + }catch(Exception exc) + { + JOptionPane.showMessageDialog(null, ""+exc, "Error in paremeter field "+inputIdx, JOptionPane.WARNING_MESSAGE); + } + } for(int fieldIdx = 0; fieldIdx < numFields[inputIdx]; fieldIdx++) { try { - subtree.putDataExpr(currInputNid + 8 + 2 * numParameters[inputIdx] + 6 * fieldIdx + 5, fieldsTF[inputIdx][fieldIdx].getText()); + subtree.putDataExpr(currInputNid + 8 + 3 * numParameters[inputIdx] + 6 * fieldIdx + 5, fieldsTF[inputIdx][fieldIdx].getText()); }catch(Exception exc) { JOptionPane.showMessageDialog(null, ""+exc, "Error in subfield of input field "+inputIdx, JOptionPane.WARNING_MESSAGE); } } - currInputNid += numInputChildren + 1 + 2 * numParameters[inputIdx] + 6 * numFields[inputIdx]; + currInputNid += numInputChildren + 1 + 3 * numParameters[inputIdx] + 6 * numFields[inputIdx]; } } } diff --git a/java/devicebeans/src/main/java/DeviceOutputs.java b/java/devicebeans/src/main/java/DeviceOutputs.java index f4985dbb6d..7d90b7677d 100644 --- a/java/devicebeans/src/main/java/DeviceOutputs.java +++ b/java/devicebeans/src/main/java/DeviceOutputs.java @@ -42,10 +42,11 @@ public int getSourceActions(JComponent comp) } private JScrollPane scrollP; private int numOutputs; - private JTextField segLensTF[], streamNamesTF[]; - private int segLenNids[], streamNameNids[]; + private JTextField segLensTF[], parametersTF[], dimensionsTF[]; + private int segLenNids[], parameterNids[], dimensionNids[]; private int numOutputChildren = 0; private int numItems; + private int numParItems; public DeviceOutputs() { } @@ -62,7 +63,7 @@ protected void initializeData(String data, boolean is_on) numOutputs = subtree.getInt("GETNCI("+subtree.getFullPath(currNid)+",\'NUMBER_OF_CHILDREN\')"); }catch(Exception exc){numOutputs = 0;} int currOutNid = currNid + 7; - //Count number of actual outputs (i.e. for which nSamomes and streamName make sense + //Count number of actual outputs (i.e. for which nSamplese make sense numItems = 0; int numBusItems = 0; for(int outIdx = 0; outIdx < numOutputs; outIdx++) @@ -91,16 +92,21 @@ protected void initializeData(String data, boolean is_on) numItems += numFields; numBusItems++; } - currOutNid += 1 + numChildren + numMembers + 2 * numPars + 8 * numFields; + numParItems += numPars; + currOutNid += 1 + numChildren + numMembers + 3 * numPars + 8 * numFields; } + dimensionsTF = new JTextField[numItems]; segLensTF = new JTextField[numItems]; - streamNamesTF = new JTextField[numItems]; + parametersTF = new JTextField[numParItems]; + + dimensionNids = new int[numItems]; segLenNids = new int[numItems]; - streamNameNids = new int[numItems]; + parameterNids = new int[numParItems]; JPanel jp = new JPanel(); jp.setLayout(new GridLayout(numItems+numBusItems, 1)); currOutNid = currNid + 7; int currItem = 0; + numParItems = 0; for(int outIdx = 0; outIdx < numOutputs; outIdx++) { int numChildren, numMembers, numPars, numFields; @@ -128,15 +134,26 @@ protected void initializeData(String data, boolean is_on) { JPanel jp1 = new JPanel(); jp1.setBorder(new TitledBorder(outName)); - jp1.setLayout(new GridLayout(1,2)); + //jp1.setLayout(new GridLayout(1,2)); + jp1.add(new JLabel("Dimensions: ")); + jp1.add(dimensionsTF[currItem] = new JTextField(4)); + dimensionNids[currItem] = currOutNid + 4; jp1.add(new JLabel("Segment len.: ")); jp1.add(segLensTF[currItem] = new JTextField(10)); - jp1.add(new JLabel("Stream name: ")); - jp1.add(streamNamesTF[currItem] = new JTextField(10)); - jp.add(jp1); segLenNids[currItem] = currOutNid + 5; - streamNameNids[currItem] = currOutNid + 6; currItem++; + for(int parIdx = 0; parIdx < numPars; parIdx++) + { + int nameNid = currOutNid + 10 + 3 * parIdx; + String parName; + try { + parName = subtree.getString(subtree.getDataExpr(nameNid)); + }catch(Exception exc){parName = "";} + jp1.add(new JLabel(parName+":")); + jp1.add(parametersTF[numParItems] = new JTextField(10)); + parameterNids[numParItems++] = currOutNid + 11 + 3 * parIdx; + } + jp.add(jp1); } else { @@ -157,9 +174,8 @@ public void mousePressed(MouseEvent me) jp.add(busLabel); for(int fieldIdx = 0; fieldIdx < numFields; fieldIdx++) { - int fieldNid = currOutNid + numChildren +numMembers +1 + 2 * numPars + 8 * fieldIdx; + int fieldNid = currOutNid + numChildren +numMembers +1 + 3 * numPars + 8 * fieldIdx; segLenNids[currItem] = fieldNid + 5; - streamNameNids[currItem] = fieldNid + 6; String fieldName = ""; try { fieldName = subtree.getString(subtree.getDataExpr(fieldNid + 1)); @@ -169,8 +185,6 @@ public void mousePressed(MouseEvent me) jp1.setLayout(new GridLayout(1,2)); jp1.add(new JLabel("Segment len.: ")); jp1.add(segLensTF[currItem] = new JTextField(10)); - jp1.add(new JLabel("Stream name: ")); - jp1.add(streamNamesTF[currItem] = new JTextField(10)); try { jp1.setTransferHandler(new FromTransferHandler(subtree.getFullPath(currOutNid)+".FIELDS."+fieldName+":VALUE")); @@ -188,7 +202,7 @@ public void mousePressed(MouseEvent me) currItem++; } } - currOutNid += 1 + numChildren + numMembers + 2 * numPars + 8 * numFields; + currOutNid += 1 + numChildren + numMembers + 3 * numPars + 8 * numFields; } scrollP = new JScrollPane(jp); @@ -198,7 +212,7 @@ public void mousePressed(MouseEvent me) } protected void displayData(String data, boolean is_on) { - for(int idx = 0; idx < numItems; idx++) +for(int idx = 0; idx < numItems; idx++) { try { segLensTF[idx].setText(subtree.getDataExpr(segLenNids[idx])); @@ -207,10 +221,19 @@ protected void displayData(String data, boolean is_on) segLensTF[idx].setText(""); } try { - streamNamesTF[idx].setText(subtree.getString(subtree.getDataExpr(streamNameNids[idx]))); + dimensionsTF[idx].setText(subtree.getDataExpr(dimensionNids[idx])); }catch(Exception exc) { - streamNamesTF[idx].setText(""); + dimensionsTF[idx].setText(""); + } + } + for(int idx = 0; idx < numParItems; idx++) + { + try { + parametersTF[idx].setText(subtree.getDataExpr(parameterNids[idx])); + }catch(Exception exc) + { + parametersTF[idx].setText(""); } } } @@ -223,15 +246,27 @@ public void apply() throws Exception for(int idx = 0; idx < numItems; idx++) { try { - subtree.putDataExpr(segLenNids[idx], segLensTF[idx].getText()); + subtree.putDataExpr(dimensionNids[idx], dimensionsTF[idx].getText()); }catch(Exception exc) - {} + { + System.out.println("Error saving Dimensions"); + } try { - String name = streamNamesTF[idx].getText(); - subtree.putDataExpr(streamNameNids[idx], "\""+streamNamesTF[idx].getText()+"\""); + subtree.putDataExpr(segLenNids[idx], segLensTF[idx].getText()); }catch(Exception exc) - {} + { + System.out.println("Error saving Segment len"); + } } - } + for(int idx = 0; idx < numParItems; idx++) + { + try { + subtree.putDataExpr(parameterNids[idx], parametersTF[idx].getText()); + }catch(Exception exc) + { + System.out.println("Error saving Parameter"); + } +} + } } diff --git a/java/jdevices/src/main/java/BCM_CONFIGSetup.java b/java/jdevices/src/main/java/BCM_CONFIGSetup.java new file mode 100644 index 0000000000..a9055291ab --- /dev/null +++ b/java/jdevices/src/main/java/BCM_CONFIGSetup.java @@ -0,0 +1,945 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author taliercio + */ +public class BCM_CONFIGSetup extends DeviceSetup { + + /** + * Creates new form BCM_CONFIGSetup + */ + public BCM_CONFIGSetup() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + deviceFieldBeanInfo1 = new DeviceFieldBeanInfo(); + jPanel1 = new javax.swing.JPanel(); + jPanel2 = new javax.swing.JPanel(); + deviceField1 = new DeviceField(); + deviceDispatch1 = new DeviceDispatch(); + deviceButtons1 = new DeviceButtons(); + jPanel3 = new javax.swing.JPanel(); + jTabbedPane1 = new javax.swing.JTabbedPane(); + jPanel4 = new javax.swing.JPanel(); + jPanel5 = new javax.swing.JPanel(); + jPanel6 = new javax.swing.JPanel(); + deviceChoice1 = new DeviceChoice(); + deviceField2 = new DeviceField(); + deviceField3 = new DeviceField(); + deviceField4 = new DeviceField(); + jPanel7 = new javax.swing.JPanel(); + deviceField5 = new DeviceField(); + deviceField7 = new DeviceField(); + deviceField14 = new DeviceField(); + jPanel8 = new javax.swing.JPanel(); + deviceField10 = new DeviceField(); + deviceField11 = new DeviceField(); + deviceField6 = new DeviceField(); + jPanel9 = new javax.swing.JPanel(); + deviceField12 = new DeviceField(); + deviceField9 = new DeviceField(); + deviceField13 = new DeviceField(); + jPanel10 = new javax.swing.JPanel(); + jPanel11 = new javax.swing.JPanel(); + jPanel12 = new javax.swing.JPanel(); + deviceChoice2 = new DeviceChoice(); + deviceField8 = new DeviceField(); + deviceField15 = new DeviceField(); + deviceField16 = new DeviceField(); + jPanel13 = new javax.swing.JPanel(); + deviceField17 = new DeviceField(); + deviceField18 = new DeviceField(); + deviceField19 = new DeviceField(); + jPanel14 = new javax.swing.JPanel(); + deviceField20 = new DeviceField(); + deviceField21 = new DeviceField(); + deviceField22 = new DeviceField(); + jPanel15 = new javax.swing.JPanel(); + deviceField23 = new DeviceField(); + deviceField24 = new DeviceField(); + deviceField25 = new DeviceField(); + jPanel16 = new javax.swing.JPanel(); + jPanel17 = new javax.swing.JPanel(); + jPanel18 = new javax.swing.JPanel(); + deviceChoice3 = new DeviceChoice(); + deviceField26 = new DeviceField(); + deviceField27 = new DeviceField(); + deviceField28 = new DeviceField(); + jPanel19 = new javax.swing.JPanel(); + deviceField29 = new DeviceField(); + deviceField30 = new DeviceField(); + deviceField31 = new DeviceField(); + jPanel20 = new javax.swing.JPanel(); + deviceField32 = new DeviceField(); + deviceField33 = new DeviceField(); + deviceField34 = new DeviceField(); + jPanel21 = new javax.swing.JPanel(); + deviceField35 = new DeviceField(); + deviceField36 = new DeviceField(); + deviceField37 = new DeviceField(); + jPanel22 = new javax.swing.JPanel(); + jPanel23 = new javax.swing.JPanel(); + jPanel24 = new javax.swing.JPanel(); + deviceChoice4 = new DeviceChoice(); + deviceField38 = new DeviceField(); + deviceField39 = new DeviceField(); + deviceField40 = new DeviceField(); + jPanel25 = new javax.swing.JPanel(); + deviceField41 = new DeviceField(); + deviceField42 = new DeviceField(); + deviceField43 = new DeviceField(); + jPanel26 = new javax.swing.JPanel(); + deviceField44 = new DeviceField(); + deviceField45 = new DeviceField(); + deviceField46 = new DeviceField(); + jPanel27 = new javax.swing.JPanel(); + deviceField47 = new DeviceField(); + deviceField48 = new DeviceField(); + deviceField49 = new DeviceField(); + jPanel28 = new javax.swing.JPanel(); + jPanel29 = new javax.swing.JPanel(); + jPanel30 = new javax.swing.JPanel(); + deviceChoice5 = new DeviceChoice(); + deviceField50 = new DeviceField(); + deviceField51 = new DeviceField(); + deviceField52 = new DeviceField(); + jPanel31 = new javax.swing.JPanel(); + deviceField53 = new DeviceField(); + deviceField54 = new DeviceField(); + deviceField55 = new DeviceField(); + jPanel32 = new javax.swing.JPanel(); + deviceField56 = new DeviceField(); + deviceField57 = new DeviceField(); + deviceField58 = new DeviceField(); + jPanel33 = new javax.swing.JPanel(); + deviceField59 = new DeviceField(); + deviceField60 = new DeviceField(); + deviceField61 = new DeviceField(); + jPanel34 = new javax.swing.JPanel(); + jPanel35 = new javax.swing.JPanel(); + jPanel36 = new javax.swing.JPanel(); + deviceChoice6 = new DeviceChoice(); + deviceField62 = new DeviceField(); + deviceField63 = new DeviceField(); + deviceField64 = new DeviceField(); + jPanel37 = new javax.swing.JPanel(); + deviceField65 = new DeviceField(); + deviceField66 = new DeviceField(); + deviceField67 = new DeviceField(); + jPanel38 = new javax.swing.JPanel(); + deviceField68 = new DeviceField(); + deviceField69 = new DeviceField(); + deviceField70 = new DeviceField(); + jPanel39 = new javax.swing.JPanel(); + deviceField71 = new DeviceField(); + deviceField72 = new DeviceField(); + deviceField73 = new DeviceField(); + + setDeviceProvider("soserver.nbtf:9000"); + setDeviceTitle("Beam Current Monitor Timing Configuration"); + setDeviceType("BCM_CONFIG"); + setHeight(360); + setWidth(1050); + + jPanel1.add(jPanel2); + + deviceField1.setIdentifier(""); + deviceField1.setLabelString("Comment:"); + deviceField1.setNumCols(60); + deviceField1.setOffsetNid(1); + deviceField1.setTextOnly(true); + jPanel1.add(deviceField1); + jPanel1.add(deviceDispatch1); + + getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH); + getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); + + jPanel3.setLayout(new java.awt.BorderLayout()); + + jPanel4.setLayout(new java.awt.GridLayout(1, 1)); + + jPanel5.setLayout(new java.awt.GridLayout(4, 1)); + + jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceChoice1.setChoiceItems(new String[] {"CONTINUOUS", "SLOW", "FAST"}); + deviceChoice1.setIdentifier(""); + deviceChoice1.setLabelString("Mode:"); + deviceChoice1.setOffsetNid(4); + deviceChoice1.setUpdateIdentifier(""); + jPanel6.add(deviceChoice1); + + deviceField2.setIdentifier(""); + deviceField2.setLabelString("Dev. Path"); + deviceField2.setNumCols(25); + deviceField2.setOffsetNid(3); + jPanel6.add(deviceField2); + + deviceField3.setIdentifier(""); + deviceField3.setLabelString("Start Time [s]:"); + deviceField3.setOffsetNid(5); + jPanel6.add(deviceField3); + + deviceField4.setIdentifier(""); + deviceField4.setLabelString("End Time [s]:"); + deviceField4.setOffsetNid(6); + jPanel6.add(deviceField4); + + jPanel5.add(jPanel6); + + jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Continuous")); + jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField5.setIdentifier(""); + deviceField5.setLabelString("Trig. source:"); + deviceField5.setNumCols(35); + deviceField5.setOffsetNid(17); + jPanel7.add(deviceField5); + + deviceField7.setIdentifier(""); + deviceField7.setLabelString("Freq [Hz]:"); + deviceField7.setNumCols(15); + deviceField7.setOffsetNid(9); + jPanel7.add(deviceField7); + + deviceField14.setIdentifier(""); + deviceField14.setLabelString("MDS event:"); + deviceField14.setNumCols(15); + deviceField14.setOffsetNid(14); + deviceField14.setTextOnly(true); + jPanel7.add(deviceField14); + + jPanel5.add(jPanel7); + + jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Slow")); + jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField10.setIdentifier(""); + deviceField10.setLabelString("Trig. source:"); + deviceField10.setNumCols(35); + deviceField10.setOffsetNid(15); + jPanel8.add(deviceField10); + + deviceField11.setIdentifier(""); + deviceField11.setLabelString("Freq [Hz]:"); + deviceField11.setNumCols(15); + deviceField11.setOffsetNid(11); + jPanel8.add(deviceField11); + + deviceField6.setIdentifier(""); + deviceField6.setLabelString("MDS event:"); + deviceField6.setNumCols(15); + deviceField6.setOffsetNid(12); + deviceField6.setTextOnly(true); + jPanel8.add(deviceField6); + + jPanel5.add(jPanel8); + + jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder("Fast")); + jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField12.setIdentifier(""); + deviceField12.setLabelString("Trig. source:"); + deviceField12.setNumCols(35); + deviceField12.setOffsetNid(16); + jPanel9.add(deviceField12); + + deviceField9.setIdentifier(""); + deviceField9.setLabelString("Freq [Hz]:"); + deviceField9.setNumCols(15); + deviceField9.setOffsetNid(10); + jPanel9.add(deviceField9); + + deviceField13.setIdentifier(""); + deviceField13.setLabelString("MDS event:"); + deviceField13.setNumCols(15); + deviceField13.setOffsetNid(13); + deviceField13.setTextOnly(true); + jPanel9.add(deviceField13); + + jPanel5.add(jPanel9); + + jPanel4.add(jPanel5); + + jTabbedPane1.addTab("CONFIG 1", jPanel4); + + jPanel10.setLayout(new java.awt.GridLayout(1, 1)); + + jPanel11.setLayout(new java.awt.GridLayout(4, 1)); + + jPanel12.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceChoice2.setChoiceItems(new String[] {"CONTINUOUS", "SLOW", "FAST"}); + deviceChoice2.setIdentifier(""); + deviceChoice2.setLabelString("Mode:"); + deviceChoice2.setOffsetNid(23); + deviceChoice2.setUpdateIdentifier(""); + jPanel12.add(deviceChoice2); + + deviceField8.setIdentifier(""); + deviceField8.setLabelString("Dev. Path"); + deviceField8.setNumCols(25); + deviceField8.setOffsetNid(22); + jPanel12.add(deviceField8); + + deviceField15.setIdentifier(""); + deviceField15.setLabelString("Start Time [s]:"); + deviceField15.setOffsetNid(24); + jPanel12.add(deviceField15); + + deviceField16.setIdentifier(""); + deviceField16.setLabelString("End Time [s]:"); + deviceField16.setOffsetNid(25); + jPanel12.add(deviceField16); + + jPanel11.add(jPanel12); + + jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder("Continuous")); + jPanel13.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField17.setIdentifier(""); + deviceField17.setLabelString("Trig. source:"); + deviceField17.setNumCols(35); + deviceField17.setOffsetNid(36); + jPanel13.add(deviceField17); + + deviceField18.setIdentifier(""); + deviceField18.setLabelString("Freq [Hz]:"); + deviceField18.setNumCols(15); + deviceField18.setOffsetNid(28); + jPanel13.add(deviceField18); + + deviceField19.setIdentifier(""); + deviceField19.setLabelString("MDS event:"); + deviceField19.setNumCols(15); + deviceField19.setOffsetNid(33); + deviceField19.setTextOnly(true); + jPanel13.add(deviceField19); + + jPanel11.add(jPanel13); + + jPanel14.setBorder(javax.swing.BorderFactory.createTitledBorder("Slow")); + jPanel14.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField20.setIdentifier(""); + deviceField20.setLabelString("Trig. source:"); + deviceField20.setNumCols(35); + deviceField20.setOffsetNid(34); + jPanel14.add(deviceField20); + + deviceField21.setIdentifier(""); + deviceField21.setLabelString("Freq [Hz]:"); + deviceField21.setNumCols(15); + deviceField21.setOffsetNid(30); + jPanel14.add(deviceField21); + + deviceField22.setIdentifier(""); + deviceField22.setLabelString("MDS event:"); + deviceField22.setNumCols(15); + deviceField22.setOffsetNid(31); + deviceField22.setTextOnly(true); + jPanel14.add(deviceField22); + + jPanel11.add(jPanel14); + + jPanel15.setBorder(javax.swing.BorderFactory.createTitledBorder("Fast")); + jPanel15.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField23.setIdentifier(""); + deviceField23.setLabelString("Trig. source:"); + deviceField23.setNumCols(35); + deviceField23.setOffsetNid(35); + jPanel15.add(deviceField23); + + deviceField24.setIdentifier(""); + deviceField24.setLabelString("Freq [Hz]:"); + deviceField24.setNumCols(15); + deviceField24.setOffsetNid(29); + jPanel15.add(deviceField24); + + deviceField25.setIdentifier(""); + deviceField25.setLabelString("MDS event:"); + deviceField25.setNumCols(15); + deviceField25.setOffsetNid(32); + deviceField25.setTextOnly(true); + jPanel15.add(deviceField25); + + jPanel11.add(jPanel15); + + jPanel10.add(jPanel11); + + jTabbedPane1.addTab("CONFIG 2", jPanel10); + + jPanel16.setLayout(new java.awt.GridLayout(1, 1)); + + jPanel17.setLayout(new java.awt.GridLayout(4, 1)); + + jPanel18.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceChoice3.setChoiceItems(new String[] {"CONTINUOUS", "SLOW", "FAST"}); + deviceChoice3.setIdentifier(""); + deviceChoice3.setLabelString("Mode:"); + deviceChoice3.setOffsetNid(42); + deviceChoice3.setUpdateIdentifier(""); + jPanel18.add(deviceChoice3); + + deviceField26.setIdentifier(""); + deviceField26.setLabelString("Dev. Path"); + deviceField26.setNumCols(25); + deviceField26.setOffsetNid(41); + jPanel18.add(deviceField26); + + deviceField27.setIdentifier(""); + deviceField27.setLabelString("Start Time [s]:"); + deviceField27.setOffsetNid(43); + jPanel18.add(deviceField27); + + deviceField28.setIdentifier(""); + deviceField28.setLabelString("End Time [s]:"); + deviceField28.setOffsetNid(44); + jPanel18.add(deviceField28); + + jPanel17.add(jPanel18); + + jPanel19.setBorder(javax.swing.BorderFactory.createTitledBorder("Continuous")); + jPanel19.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField29.setIdentifier(""); + deviceField29.setLabelString("Trig. source:"); + deviceField29.setNumCols(35); + deviceField29.setOffsetNid(55); + jPanel19.add(deviceField29); + + deviceField30.setIdentifier(""); + deviceField30.setLabelString("Freq [Hz]:"); + deviceField30.setNumCols(15); + deviceField30.setOffsetNid(47); + jPanel19.add(deviceField30); + + deviceField31.setIdentifier(""); + deviceField31.setLabelString("MDS event:"); + deviceField31.setNumCols(15); + deviceField31.setOffsetNid(52); + deviceField31.setTextOnly(true); + jPanel19.add(deviceField31); + + jPanel17.add(jPanel19); + + jPanel20.setBorder(javax.swing.BorderFactory.createTitledBorder("Slow")); + jPanel20.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField32.setIdentifier(""); + deviceField32.setLabelString("Trig. source:"); + deviceField32.setNumCols(35); + deviceField32.setOffsetNid(53); + jPanel20.add(deviceField32); + + deviceField33.setIdentifier(""); + deviceField33.setLabelString("Freq [Hz]:"); + deviceField33.setNumCols(15); + deviceField33.setOffsetNid(49); + jPanel20.add(deviceField33); + + deviceField34.setIdentifier(""); + deviceField34.setLabelString("MDS event:"); + deviceField34.setNumCols(15); + deviceField34.setOffsetNid(50); + deviceField34.setTextOnly(true); + jPanel20.add(deviceField34); + + jPanel17.add(jPanel20); + + jPanel21.setBorder(javax.swing.BorderFactory.createTitledBorder("Fast")); + jPanel21.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField35.setIdentifier(""); + deviceField35.setLabelString("Trig. source:"); + deviceField35.setNumCols(35); + deviceField35.setOffsetNid(54); + jPanel21.add(deviceField35); + + deviceField36.setIdentifier(""); + deviceField36.setLabelString("Freq [Hz]:"); + deviceField36.setNumCols(15); + deviceField36.setOffsetNid(48); + jPanel21.add(deviceField36); + + deviceField37.setIdentifier(""); + deviceField37.setLabelString("MDS event:"); + deviceField37.setNumCols(15); + deviceField37.setOffsetNid(51); + deviceField37.setTextOnly(true); + jPanel21.add(deviceField37); + + jPanel17.add(jPanel21); + + jPanel16.add(jPanel17); + + jTabbedPane1.addTab("CONFIG 3", jPanel16); + + jPanel22.setLayout(new java.awt.GridLayout(1, 1)); + + jPanel23.setLayout(new java.awt.GridLayout(4, 1)); + + jPanel24.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceChoice4.setChoiceItems(new String[] {"CONTINUOUS", "SLOW", "FAST"}); + deviceChoice4.setIdentifier(""); + deviceChoice4.setLabelString("Mode:"); + deviceChoice4.setOffsetNid(61); + deviceChoice4.setUpdateIdentifier(""); + jPanel24.add(deviceChoice4); + + deviceField38.setIdentifier(""); + deviceField38.setLabelString("Dev. Path"); + deviceField38.setNumCols(25); + deviceField38.setOffsetNid(60); + jPanel24.add(deviceField38); + + deviceField39.setIdentifier(""); + deviceField39.setLabelString("Start Time [s]:"); + deviceField39.setOffsetNid(62); + jPanel24.add(deviceField39); + + deviceField40.setIdentifier(""); + deviceField40.setLabelString("End Time [s]:"); + deviceField40.setOffsetNid(63); + jPanel24.add(deviceField40); + + jPanel23.add(jPanel24); + + jPanel25.setBorder(javax.swing.BorderFactory.createTitledBorder("Continuous")); + jPanel25.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField41.setIdentifier(""); + deviceField41.setLabelString("Trig. source:"); + deviceField41.setNumCols(35); + deviceField41.setOffsetNid(74); + jPanel25.add(deviceField41); + + deviceField42.setIdentifier(""); + deviceField42.setLabelString("Freq [Hz]:"); + deviceField42.setNumCols(15); + deviceField42.setOffsetNid(66); + jPanel25.add(deviceField42); + + deviceField43.setIdentifier(""); + deviceField43.setLabelString("MDS event:"); + deviceField43.setNumCols(15); + deviceField43.setOffsetNid(71); + deviceField43.setTextOnly(true); + jPanel25.add(deviceField43); + + jPanel23.add(jPanel25); + + jPanel26.setBorder(javax.swing.BorderFactory.createTitledBorder("Slow")); + jPanel26.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField44.setIdentifier(""); + deviceField44.setLabelString("Trig. source:"); + deviceField44.setNumCols(35); + deviceField44.setOffsetNid(72); + jPanel26.add(deviceField44); + + deviceField45.setIdentifier(""); + deviceField45.setLabelString("Freq [Hz]:"); + deviceField45.setNumCols(15); + deviceField45.setOffsetNid(68); + jPanel26.add(deviceField45); + + deviceField46.setIdentifier(""); + deviceField46.setLabelString("MDS event:"); + deviceField46.setNumCols(15); + deviceField46.setOffsetNid(69); + deviceField46.setTextOnly(true); + jPanel26.add(deviceField46); + + jPanel23.add(jPanel26); + + jPanel27.setBorder(javax.swing.BorderFactory.createTitledBorder("Fast")); + jPanel27.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField47.setIdentifier(""); + deviceField47.setLabelString("Trig. source:"); + deviceField47.setNumCols(35); + deviceField47.setOffsetNid(73); + jPanel27.add(deviceField47); + + deviceField48.setIdentifier(""); + deviceField48.setLabelString("Freq [Hz]:"); + deviceField48.setNumCols(15); + deviceField48.setOffsetNid(67); + jPanel27.add(deviceField48); + + deviceField49.setIdentifier(""); + deviceField49.setLabelString("MDS event:"); + deviceField49.setNumCols(15); + deviceField49.setOffsetNid(70); + deviceField49.setTextOnly(true); + jPanel27.add(deviceField49); + + jPanel23.add(jPanel27); + + jPanel22.add(jPanel23); + + jTabbedPane1.addTab("CONFIG 4", jPanel22); + + jPanel28.setLayout(new java.awt.GridLayout(1, 1)); + + jPanel29.setLayout(new java.awt.GridLayout(4, 1)); + + jPanel30.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceChoice5.setChoiceItems(new String[] {"CONTINUOUS", "SLOW", "FAST"}); + deviceChoice5.setIdentifier(""); + deviceChoice5.setLabelString("Mode:"); + deviceChoice5.setOffsetNid(80); + deviceChoice5.setUpdateIdentifier(""); + jPanel30.add(deviceChoice5); + + deviceField50.setIdentifier(""); + deviceField50.setLabelString("Dev. Path"); + deviceField50.setNumCols(25); + deviceField50.setOffsetNid(79); + jPanel30.add(deviceField50); + + deviceField51.setIdentifier(""); + deviceField51.setLabelString("Start Time [s]:"); + deviceField51.setOffsetNid(81); + jPanel30.add(deviceField51); + + deviceField52.setIdentifier(""); + deviceField52.setLabelString("End Time [s]:"); + deviceField52.setOffsetNid(82); + jPanel30.add(deviceField52); + + jPanel29.add(jPanel30); + + jPanel31.setBorder(javax.swing.BorderFactory.createTitledBorder("Continuous")); + jPanel31.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField53.setIdentifier(""); + deviceField53.setLabelString("Trig. source:"); + deviceField53.setNumCols(35); + deviceField53.setOffsetNid(93); + jPanel31.add(deviceField53); + + deviceField54.setIdentifier(""); + deviceField54.setLabelString("Freq [Hz]:"); + deviceField54.setNumCols(15); + deviceField54.setOffsetNid(85); + jPanel31.add(deviceField54); + + deviceField55.setIdentifier(""); + deviceField55.setLabelString("MDS event:"); + deviceField55.setNumCols(15); + deviceField55.setOffsetNid(90); + deviceField55.setTextOnly(true); + jPanel31.add(deviceField55); + + jPanel29.add(jPanel31); + + jPanel32.setBorder(javax.swing.BorderFactory.createTitledBorder("Slow")); + jPanel32.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField56.setIdentifier(""); + deviceField56.setLabelString("Trig. source:"); + deviceField56.setNumCols(35); + deviceField56.setOffsetNid(91); + jPanel32.add(deviceField56); + + deviceField57.setIdentifier(""); + deviceField57.setLabelString("Freq [Hz]:"); + deviceField57.setNumCols(15); + deviceField57.setOffsetNid(87); + jPanel32.add(deviceField57); + + deviceField58.setIdentifier(""); + deviceField58.setLabelString("MDS event:"); + deviceField58.setNumCols(15); + deviceField58.setOffsetNid(88); + deviceField58.setTextOnly(true); + jPanel32.add(deviceField58); + + jPanel29.add(jPanel32); + + jPanel33.setBorder(javax.swing.BorderFactory.createTitledBorder("Fast")); + jPanel33.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField59.setIdentifier(""); + deviceField59.setLabelString("Trig. source:"); + deviceField59.setNumCols(35); + deviceField59.setOffsetNid(92); + jPanel33.add(deviceField59); + + deviceField60.setIdentifier(""); + deviceField60.setLabelString("Freq [Hz]:"); + deviceField60.setNumCols(15); + deviceField60.setOffsetNid(86); + jPanel33.add(deviceField60); + + deviceField61.setIdentifier(""); + deviceField61.setLabelString("MDS event:"); + deviceField61.setNumCols(15); + deviceField61.setOffsetNid(89); + deviceField61.setTextOnly(true); + jPanel33.add(deviceField61); + + jPanel29.add(jPanel33); + + jPanel28.add(jPanel29); + + jTabbedPane1.addTab("CONFIG 5", jPanel28); + + jPanel34.setLayout(new java.awt.GridLayout(1, 1)); + + jPanel35.setLayout(new java.awt.GridLayout(4, 1)); + + jPanel36.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceChoice6.setChoiceItems(new String[] {"CONTINUOUS", "SLOW", "FAST"}); + deviceChoice6.setIdentifier(""); + deviceChoice6.setLabelString("Mode:"); + deviceChoice6.setOffsetNid(99); + deviceChoice6.setUpdateIdentifier(""); + jPanel36.add(deviceChoice6); + + deviceField62.setIdentifier(""); + deviceField62.setLabelString("Dev. Path"); + deviceField62.setNumCols(25); + deviceField62.setOffsetNid(98); + jPanel36.add(deviceField62); + + deviceField63.setIdentifier(""); + deviceField63.setLabelString("Start Time [s]:"); + deviceField63.setOffsetNid(100); + jPanel36.add(deviceField63); + + deviceField64.setIdentifier(""); + deviceField64.setLabelString("End Time [s]:"); + deviceField64.setOffsetNid(101); + jPanel36.add(deviceField64); + + jPanel35.add(jPanel36); + + jPanel37.setBorder(javax.swing.BorderFactory.createTitledBorder("Continuous")); + jPanel37.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField65.setIdentifier(""); + deviceField65.setLabelString("Trig. source:"); + deviceField65.setNumCols(35); + deviceField65.setOffsetNid(112); + jPanel37.add(deviceField65); + + deviceField66.setIdentifier(""); + deviceField66.setLabelString("Freq [Hz]:"); + deviceField66.setNumCols(15); + deviceField66.setOffsetNid(104); + jPanel37.add(deviceField66); + + deviceField67.setIdentifier(""); + deviceField67.setLabelString("MDS event:"); + deviceField67.setNumCols(15); + deviceField67.setOffsetNid(109); + deviceField67.setTextOnly(true); + jPanel37.add(deviceField67); + + jPanel35.add(jPanel37); + + jPanel38.setBorder(javax.swing.BorderFactory.createTitledBorder("Slow")); + jPanel38.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField68.setIdentifier(""); + deviceField68.setLabelString("Trig. source:"); + deviceField68.setNumCols(35); + deviceField68.setOffsetNid(110); + jPanel38.add(deviceField68); + + deviceField69.setIdentifier(""); + deviceField69.setLabelString("Freq [Hz]:"); + deviceField69.setNumCols(15); + deviceField69.setOffsetNid(106); + jPanel38.add(deviceField69); + + deviceField70.setIdentifier(""); + deviceField70.setLabelString("MDS event:"); + deviceField70.setNumCols(15); + deviceField70.setOffsetNid(107); + deviceField70.setTextOnly(true); + jPanel38.add(deviceField70); + + jPanel35.add(jPanel38); + + jPanel39.setBorder(javax.swing.BorderFactory.createTitledBorder("Fast")); + jPanel39.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField71.setIdentifier(""); + deviceField71.setLabelString("Trig. source:"); + deviceField71.setNumCols(35); + deviceField71.setOffsetNid(111); + jPanel39.add(deviceField71); + + deviceField72.setIdentifier(""); + deviceField72.setLabelString("Freq [Hz]:"); + deviceField72.setNumCols(15); + deviceField72.setOffsetNid(105); + jPanel39.add(deviceField72); + + deviceField73.setIdentifier(""); + deviceField73.setLabelString("MDS event:"); + deviceField73.setNumCols(15); + deviceField73.setOffsetNid(108); + deviceField73.setTextOnly(true); + jPanel39.add(deviceField73); + + jPanel35.add(jPanel39); + + jPanel34.add(jPanel35); + + jTabbedPane1.addTab("CONFIG 6", jPanel34); + + jPanel3.add(jTabbedPane1, java.awt.BorderLayout.CENTER); + + getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER); + }// //GEN-END:initComponents + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private DeviceButtons deviceButtons1; + private DeviceChoice deviceChoice1; + private DeviceChoice deviceChoice2; + private DeviceChoice deviceChoice3; + private DeviceChoice deviceChoice4; + private DeviceChoice deviceChoice5; + private DeviceChoice deviceChoice6; + private DeviceDispatch deviceDispatch1; + private DeviceField deviceField1; + private DeviceField deviceField10; + private DeviceField deviceField11; + private DeviceField deviceField12; + private DeviceField deviceField13; + private DeviceField deviceField14; + private DeviceField deviceField15; + private DeviceField deviceField16; + private DeviceField deviceField17; + private DeviceField deviceField18; + private DeviceField deviceField19; + private DeviceField deviceField2; + private DeviceField deviceField20; + private DeviceField deviceField21; + private DeviceField deviceField22; + private DeviceField deviceField23; + private DeviceField deviceField24; + private DeviceField deviceField25; + private DeviceField deviceField26; + private DeviceField deviceField27; + private DeviceField deviceField28; + private DeviceField deviceField29; + private DeviceField deviceField3; + private DeviceField deviceField30; + private DeviceField deviceField31; + private DeviceField deviceField32; + private DeviceField deviceField33; + private DeviceField deviceField34; + private DeviceField deviceField35; + private DeviceField deviceField36; + private DeviceField deviceField37; + private DeviceField deviceField38; + private DeviceField deviceField39; + private DeviceField deviceField4; + private DeviceField deviceField40; + private DeviceField deviceField41; + private DeviceField deviceField42; + private DeviceField deviceField43; + private DeviceField deviceField44; + private DeviceField deviceField45; + private DeviceField deviceField46; + private DeviceField deviceField47; + private DeviceField deviceField48; + private DeviceField deviceField49; + private DeviceField deviceField5; + private DeviceField deviceField50; + private DeviceField deviceField51; + private DeviceField deviceField52; + private DeviceField deviceField53; + private DeviceField deviceField54; + private DeviceField deviceField55; + private DeviceField deviceField56; + private DeviceField deviceField57; + private DeviceField deviceField58; + private DeviceField deviceField59; + private DeviceField deviceField6; + private DeviceField deviceField60; + private DeviceField deviceField61; + private DeviceField deviceField62; + private DeviceField deviceField63; + private DeviceField deviceField64; + private DeviceField deviceField65; + private DeviceField deviceField66; + private DeviceField deviceField67; + private DeviceField deviceField68; + private DeviceField deviceField69; + private DeviceField deviceField7; + private DeviceField deviceField70; + private DeviceField deviceField71; + private DeviceField deviceField72; + private DeviceField deviceField73; + private DeviceField deviceField8; + private DeviceField deviceField9; + private DeviceFieldBeanInfo deviceFieldBeanInfo1; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel10; + private javax.swing.JPanel jPanel11; + private javax.swing.JPanel jPanel12; + private javax.swing.JPanel jPanel13; + private javax.swing.JPanel jPanel14; + private javax.swing.JPanel jPanel15; + private javax.swing.JPanel jPanel16; + private javax.swing.JPanel jPanel17; + private javax.swing.JPanel jPanel18; + private javax.swing.JPanel jPanel19; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel20; + private javax.swing.JPanel jPanel21; + private javax.swing.JPanel jPanel22; + private javax.swing.JPanel jPanel23; + private javax.swing.JPanel jPanel24; + private javax.swing.JPanel jPanel25; + private javax.swing.JPanel jPanel26; + private javax.swing.JPanel jPanel27; + private javax.swing.JPanel jPanel28; + private javax.swing.JPanel jPanel29; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel30; + private javax.swing.JPanel jPanel31; + private javax.swing.JPanel jPanel32; + private javax.swing.JPanel jPanel33; + private javax.swing.JPanel jPanel34; + private javax.swing.JPanel jPanel35; + private javax.swing.JPanel jPanel36; + private javax.swing.JPanel jPanel37; + private javax.swing.JPanel jPanel38; + private javax.swing.JPanel jPanel39; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel jPanel6; + private javax.swing.JPanel jPanel7; + private javax.swing.JPanel jPanel8; + private javax.swing.JPanel jPanel9; + private javax.swing.JTabbedPane jTabbedPane1; + // End of variables declaration//GEN-END:variables +} diff --git a/java/jdevices/src/main/java/DTACQ_SUPERVISORSetup.java b/java/jdevices/src/main/java/DTACQ_SUPERVISORSetup.java index 9da52b6581..e3c7708af9 100644 --- a/java/jdevices/src/main/java/DTACQ_SUPERVISORSetup.java +++ b/java/jdevices/src/main/java/DTACQ_SUPERVISORSetup.java @@ -66,6 +66,44 @@ private void initComponents() { jPanel16 = new javax.swing.JPanel(); deviceField15 = new DeviceField(); deviceField16 = new DeviceField(); + jScrollPane1 = new javax.swing.JScrollPane(); + jPanel17 = new javax.swing.JPanel(); + jPanel18 = new javax.swing.JPanel(); + deviceField18 = new DeviceField(); + deviceChoice6 = new DeviceChoice(); + jPanel19 = new javax.swing.JPanel(); + deviceChoice7 = new DeviceChoice(); + deviceField19 = new DeviceField(); + deviceField32 = new DeviceField(); + jPanel20 = new javax.swing.JPanel(); + deviceField20 = new DeviceField(); + jPanel21 = new javax.swing.JPanel(); + deviceField21 = new DeviceField(); + jPanel22 = new javax.swing.JPanel(); + deviceField22 = new DeviceField(); + jPanel23 = new javax.swing.JPanel(); + deviceField23 = new DeviceField(); + jPanel24 = new javax.swing.JPanel(); + deviceField24 = new DeviceField(); + jScrollPane2 = new javax.swing.JScrollPane(); + jPanel25 = new javax.swing.JPanel(); + jPanel26 = new javax.swing.JPanel(); + deviceField25 = new DeviceField(); + deviceChoice8 = new DeviceChoice(); + jPanel27 = new javax.swing.JPanel(); + deviceChoice9 = new DeviceChoice(); + deviceField26 = new DeviceField(); + deviceField33 = new DeviceField(); + jPanel28 = new javax.swing.JPanel(); + deviceField27 = new DeviceField(); + jPanel29 = new javax.swing.JPanel(); + deviceField28 = new DeviceField(); + jPanel30 = new javax.swing.JPanel(); + deviceField29 = new DeviceField(); + jPanel31 = new javax.swing.JPanel(); + deviceField30 = new DeviceField(); + jPanel32 = new javax.swing.JPanel(); + deviceField31 = new DeviceField(); setDeviceProvider("localhost:8100"); setDeviceTitle("DTACQ Supervisor"); @@ -249,6 +287,170 @@ private void initComponents() { jTabbedPane1.addTab("Clock/Trigger", jPanel14); + jPanel17.setLayout(new java.awt.GridLayout(7, 1)); + + deviceField18.setIdentifier(""); + deviceField18.setLabelString("Site"); + deviceField18.setNumCols(5); + deviceField18.setOffsetNid(24); + jPanel18.add(deviceField18); + + deviceChoice6.setChoiceItems(new String[] {"TRIG_IN", "SOFTWARE", "ADC_TRIG", "SITE4_TRIG", "SITE5_TRIG"}); + deviceChoice6.setIdentifier(""); + deviceChoice6.setLabelString("Trig. Source: "); + deviceChoice6.setOffsetNid(25); + deviceChoice6.setUpdateIdentifier(""); + jPanel18.add(deviceChoice6); + + jPanel17.add(jPanel18); + + deviceChoice7.setChoiceItems(new String[] {"SINGLE", "LOOP", "LOOPWAIT"}); + deviceChoice7.setIdentifier(""); + deviceChoice7.setLabelString("Mode: "); + deviceChoice7.setOffsetNid(26); + deviceChoice7.setUpdateIdentifier(""); + jPanel19.add(deviceChoice7); + + deviceField19.setIdentifier(""); + deviceField19.setLabelString("Time Division: "); + deviceField19.setNumCols(8); + deviceField19.setOffsetNid(27); + jPanel19.add(deviceField19); + + deviceField32.setIdentifier(""); + deviceField32.setLabelString("Loop Period: "); + deviceField32.setNumCols(8); + deviceField32.setOffsetNid(28); + jPanel19.add(deviceField32); + + jPanel17.add(jPanel19); + + deviceField20.setIdentifier(""); + deviceField20.setLabelString("D1 Times: "); + deviceField20.setNumCols(30); + deviceField20.setOffsetNid(29); + jPanel20.add(deviceField20); + + jPanel17.add(jPanel20); + + deviceField21.setIdentifier(""); + deviceField21.setLabelString("D2 Times: "); + deviceField21.setNumCols(30); + deviceField21.setOffsetNid(30); + jPanel21.add(deviceField21); + + jPanel17.add(jPanel21); + + deviceField22.setIdentifier(""); + deviceField22.setLabelString("D3 Times: "); + deviceField22.setNumCols(30); + deviceField22.setOffsetNid(31); + jPanel22.add(deviceField22); + + jPanel17.add(jPanel22); + + deviceField23.setIdentifier(""); + deviceField23.setLabelString("D4 Times: "); + deviceField23.setNumCols(30); + deviceField23.setOffsetNid(32); + jPanel23.add(deviceField23); + + jPanel17.add(jPanel23); + + deviceField24.setIdentifier(""); + deviceField24.setLabelString("D5 Times: "); + deviceField24.setNumCols(30); + deviceField24.setOffsetNid(33); + jPanel24.add(deviceField24); + + jPanel17.add(jPanel24); + + jScrollPane1.setViewportView(jPanel17); + + jTabbedPane1.addTab("PG1", jScrollPane1); + + jPanel25.setLayout(new java.awt.GridLayout(7, 1)); + + deviceField25.setIdentifier(""); + deviceField25.setLabelString("Site"); + deviceField25.setNumCols(5); + deviceField25.setOffsetNid(35); + jPanel26.add(deviceField25); + + deviceChoice8.setChoiceItems(new String[] {"TRIG_IN", "SOFTWARE", "ADC_TRIG", "SITE4_TRIG", "SITE5_TRIG"}); + deviceChoice8.setIdentifier(""); + deviceChoice8.setLabelString("Trig. Source: "); + deviceChoice8.setOffsetNid(36); + deviceChoice8.setUpdateIdentifier(""); + jPanel26.add(deviceChoice8); + + jPanel25.add(jPanel26); + + deviceChoice9.setChoiceItems(new String[] {"SINGLE", "LOOP", "LOOPWAIT"}); + deviceChoice9.setIdentifier(""); + deviceChoice9.setLabelString("Mode: "); + deviceChoice9.setOffsetNid(37); + deviceChoice9.setUpdateIdentifier(""); + jPanel27.add(deviceChoice9); + + deviceField26.setIdentifier(""); + deviceField26.setLabelString("Time Division: "); + deviceField26.setNumCols(8); + deviceField26.setOffsetNid(38); + jPanel27.add(deviceField26); + + deviceField33.setIdentifier(""); + deviceField33.setLabelString("Loop period: "); + deviceField33.setNumCols(8); + deviceField33.setOffsetNid(39); + jPanel27.add(deviceField33); + + jPanel25.add(jPanel27); + + deviceField27.setIdentifier(""); + deviceField27.setLabelString("D1 Times: "); + deviceField27.setNumCols(30); + deviceField27.setOffsetNid(40); + jPanel28.add(deviceField27); + + jPanel25.add(jPanel28); + + deviceField28.setIdentifier(""); + deviceField28.setLabelString("D2 Times: "); + deviceField28.setNumCols(30); + deviceField28.setOffsetNid(41); + jPanel29.add(deviceField28); + + jPanel25.add(jPanel29); + + deviceField29.setIdentifier(""); + deviceField29.setLabelString("D3 Times: "); + deviceField29.setNumCols(30); + deviceField29.setOffsetNid(42); + jPanel30.add(deviceField29); + + jPanel25.add(jPanel30); + + deviceField30.setIdentifier(""); + deviceField30.setLabelString("D4 Times: "); + deviceField30.setNumCols(30); + deviceField30.setOffsetNid(43); + jPanel31.add(deviceField30); + + jPanel25.add(jPanel31); + + deviceField31.setIdentifier(""); + deviceField31.setLabelString("D5 Times: "); + deviceField31.setNumCols(30); + deviceField31.setOffsetNid(44); + jPanel32.add(deviceField31); + + jPanel25.add(jPanel32); + + jScrollPane2.setViewportView(jPanel25); + + jTabbedPane1.addTab("PG2", jScrollPane2); + getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); }// //GEN-END:initComponents @@ -260,6 +462,10 @@ private void initComponents() { private DeviceChoice deviceChoice3; private DeviceChoice deviceChoice4; private DeviceChoice deviceChoice5; + private DeviceChoice deviceChoice6; + private DeviceChoice deviceChoice7; + private DeviceChoice deviceChoice8; + private DeviceChoice deviceChoice9; private DeviceField deviceField1; private DeviceField deviceField10; private DeviceField deviceField11; @@ -269,8 +475,24 @@ private void initComponents() { private DeviceField deviceField15; private DeviceField deviceField16; private DeviceField deviceField17; + private DeviceField deviceField18; + private DeviceField deviceField19; private DeviceField deviceField2; + private DeviceField deviceField20; + private DeviceField deviceField21; + private DeviceField deviceField22; + private DeviceField deviceField23; + private DeviceField deviceField24; + private DeviceField deviceField25; + private DeviceField deviceField26; + private DeviceField deviceField27; + private DeviceField deviceField28; + private DeviceField deviceField29; private DeviceField deviceField3; + private DeviceField deviceField30; + private DeviceField deviceField31; + private DeviceField deviceField32; + private DeviceField deviceField33; private DeviceField deviceField4; private DeviceField deviceField5; private DeviceField deviceField6; @@ -285,14 +507,32 @@ private void initComponents() { private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel16; + private javax.swing.JPanel jPanel17; + private javax.swing.JPanel jPanel18; + private javax.swing.JPanel jPanel19; private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel20; + private javax.swing.JPanel jPanel21; + private javax.swing.JPanel jPanel22; + private javax.swing.JPanel jPanel23; + private javax.swing.JPanel jPanel24; + private javax.swing.JPanel jPanel25; + private javax.swing.JPanel jPanel26; + private javax.swing.JPanel jPanel27; + private javax.swing.JPanel jPanel28; + private javax.swing.JPanel jPanel29; private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel30; + private javax.swing.JPanel jPanel31; + private javax.swing.JPanel jPanel32; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; // End of variables declaration//GEN-END:variables } diff --git a/java/jdevices/src/main/java/MITICA_SETUPSetup.java b/java/jdevices/src/main/java/MITICA_SETUPSetup.java index 4d43ed2bd9..681e6875f3 100644 --- a/java/jdevices/src/main/java/MITICA_SETUPSetup.java +++ b/java/jdevices/src/main/java/MITICA_SETUPSetup.java @@ -63,6 +63,12 @@ private void initComponents() { jPanel54 = new javax.swing.JPanel(); deviceField29 = new DeviceField(); deviceChoice10 = new DeviceChoice(); + jPanel34 = new javax.swing.JPanel(); + jPanel24 = new javax.swing.JPanel(); + deviceChoice3 = new DeviceChoice(); + deviceField41 = new DeviceField(); + deviceField21 = new DeviceField(); + deviceField22 = new DeviceField(); jPanel52 = new javax.swing.JPanel(); deviceField42 = new DeviceField(); deviceField43 = new DeviceField(); @@ -89,8 +95,6 @@ private void initComponents() { deviceWave3 = new DeviceWave(); jPanel13 = new javax.swing.JPanel(); deviceWave6 = new DeviceWave(); - jPanel56 = new javax.swing.JPanel(); - deviceWave14 = new DeviceWave(); jTabbedPane7 = new javax.swing.JTabbedPane(); jPanel10 = new javax.swing.JPanel(); deviceWave4 = new DeviceWave(); @@ -163,18 +167,15 @@ private void initComponents() { deviceField38 = new DeviceField(); deviceField39 = new DeviceField(); jPanel18 = new javax.swing.JPanel(); - jPanel19 = new javax.swing.JPanel(); - jPanel41 = new javax.swing.JPanel(); jPanel20 = new javax.swing.JPanel(); deviceField12 = new DeviceField(); + jPanel19 = new javax.swing.JPanel(); + jTabbedPane11 = new javax.swing.JTabbedPane(); + jPanel56 = new javax.swing.JPanel(); jPanel43 = new javax.swing.JPanel(); jPanel42 = new javax.swing.JPanel(); deviceField40 = new DeviceField(); jPanel55 = new javax.swing.JPanel(); - deviceField26 = new DeviceField(); - jLabel1 = new javax.swing.JLabel(); - deviceField27 = new DeviceField(); - jLabel2 = new javax.swing.JLabel(); deviceChoice11 = new DeviceChoice(); deviceChoice12 = new DeviceChoice(); jTabbedPane4 = new javax.swing.JTabbedPane(); @@ -184,15 +185,38 @@ private void initComponents() { deviceWave11 = new DeviceWave(); jPanel23 = new javax.swing.JPanel(); deviceWave12 = new DeviceWave(); - - setDeviceProvider("soserver.nbtf:9000"); + jPanel41 = new javax.swing.JPanel(); + deviceWave18 = new DeviceWave(); + jPanel75 = new javax.swing.JPanel(); + deviceWave19 = new DeviceWave(); + jPanel57 = new javax.swing.JPanel(); + jPanel58 = new javax.swing.JPanel(); + jPanel69 = new javax.swing.JPanel(); + deviceField44 = new DeviceField(); + jPanel70 = new javax.swing.JPanel(); + deviceField45 = new DeviceField(); + jLabel3 = new javax.swing.JLabel(); + deviceField46 = new DeviceField(); + jLabel4 = new javax.swing.JLabel(); + deviceField47 = new DeviceField(); + jLabel5 = new javax.swing.JLabel(); + deviceChoice13 = new DeviceChoice(); + deviceChoice14 = new DeviceChoice(); + jTabbedPane12 = new javax.swing.JTabbedPane(); + jPanel71 = new javax.swing.JPanel(); + deviceWave14 = new DeviceWave(); + jPanel72 = new javax.swing.JPanel(); + deviceWave15 = new DeviceWave(); + jPanel73 = new javax.swing.JPanel(); + deviceWave16 = new DeviceWave(); + jPanel74 = new javax.swing.JPanel(); + deviceWave17 = new DeviceWave(); + + setDeviceProvider("saserver.nbtf:9000"); setDeviceTitle("MITICA Experiment Setup"); setDeviceType("MITICA_SETUP"); - setHeight(650); - setWidth(1200); - - deviceButtons1.setCheckExpressions(new String[] {}); - deviceButtons1.setCheckMessages(new String[] {}); + setHeight(800); + setWidth(1000); getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END); jTabbedPane1.addFocusListener(new java.awt.event.FocusAdapter() { @@ -238,11 +262,6 @@ public void focusLost(java.awt.event.FocusEvent evt) { jPanel28.add(jPanel30); jPanel29.setBorder(javax.swing.BorderFactory.createTitledBorder("Reference Waveform Time Limit")); - jPanel29.addFocusListener(new java.awt.event.FocusAdapter() { - public void focusLost(java.awt.event.FocusEvent evt) { - jPanel29FocusLost(evt); - } - }); deviceField13.setIdentifier(""); deviceField13.setLabelString("Start Time: "); @@ -284,7 +303,7 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { jPanel17.setLayout(new java.awt.BorderLayout()); - jPanel3.setLayout(new java.awt.GridLayout(3, 0)); + jPanel3.setLayout(new java.awt.GridLayout(4, 0)); jPanel32.setBorder(javax.swing.BorderFactory.createTitledBorder("EG Modulation")); @@ -329,7 +348,7 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { jPanel33.add(jPanel53); - deviceField29.setIdentifier("isrf_te_v"); + deviceField29.setIdentifier(""); deviceField29.setLabelString("ISRF TE V:"); deviceField29.setOffsetNid(323); jPanel54.add(deviceField29); @@ -345,6 +364,38 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { jPanel3.add(jPanel33); + jPanel34.setBorder(javax.swing.BorderFactory.createTitledBorder("Filament")); + jPanel34.setLayout(new java.awt.GridLayout(2, 0)); + + deviceChoice3.setChoiceItems(new String[] {"ON", "OFF"}); + deviceChoice3.setIdentifier(""); + deviceChoice3.setLabelString("State:"); + deviceChoice3.setOffsetNid(130); + deviceChoice3.setUpdateIdentifier(""); + jPanel24.add(deviceChoice3); + + deviceField41.setIdentifier(""); + deviceField41.setLabelString("Ref. V:"); + deviceField41.setNumCols(8); + deviceField41.setOffsetNid(325); + jPanel24.add(deviceField41); + + deviceField21.setIdentifier(""); + deviceField21.setLabelString("Start Time:"); + deviceField21.setNumCols(20); + deviceField21.setOffsetNid(131); + jPanel24.add(deviceField21); + + deviceField22.setIdentifier(""); + deviceField22.setLabelString("Stop Time:"); + deviceField22.setNumCols(20); + deviceField22.setOffsetNid(132); + jPanel24.add(deviceField22); + + jPanel34.add(jPanel24); + + jPanel3.add(jPanel34); + jPanel52.setBorder(javax.swing.BorderFactory.createTitledBorder("Core Snubber")); deviceField42.setIdentifier(""); @@ -478,18 +529,9 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { jTabbedPane2.addTab("Bias I/V [A]/[V]", jPanel13); - jPanel56.setLayout(new java.awt.BorderLayout()); - - deviceWave14.setIdentifier(""); - deviceWave14.setOffsetNid(269); - deviceWave14.setUpdateExpression(""); - jPanel56.add(deviceWave14, java.awt.BorderLayout.CENTER); - - jTabbedPane2.addTab("Filament Bias [V] ", jPanel56); - jPanel10.setLayout(new java.awt.BorderLayout()); - deviceWave4.setIdentifier("rf1_power"); + deviceWave4.setIdentifier(""); deviceWave4.setOffsetNid(39); deviceWave4.setUpdateExpression(""); jPanel10.add(deviceWave4, java.awt.BorderLayout.CENTER); @@ -512,13 +554,13 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { deviceWave22.setUpdateExpression(""); jPanel48.add(deviceWave22, java.awt.BorderLayout.CENTER); - jTabbedPane7.addTab("RF1 Capacitance [pF]", jPanel48); + jTabbedPane7.addTab("RF1 Capacitance [nF]", jPanel48); jTabbedPane2.addTab("RF1 Setup", jTabbedPane7); jPanel15.setLayout(new java.awt.BorderLayout()); - deviceWave8.setIdentifier("rf2_power"); + deviceWave8.setIdentifier(""); deviceWave8.setOffsetNid(57); deviceWave8.setUpdateExpression(""); jPanel15.add(deviceWave8, java.awt.BorderLayout.CENTER); @@ -541,13 +583,13 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { deviceWave23.setUpdateExpression(""); jPanel49.add(deviceWave23, java.awt.BorderLayout.CENTER); - jTabbedPane8.addTab("RF2 Capacitance [pF]", jPanel49); + jTabbedPane8.addTab("RF2 Capacitance [nF]", jPanel49); jTabbedPane2.addTab("RF2 Setup", jTabbedPane8); jPanel50.setLayout(new java.awt.BorderLayout()); - deviceWave24.setIdentifier("rf3_power"); + deviceWave24.setIdentifier(""); deviceWave24.setOffsetNid(227); deviceWave24.setUpdateExpression(""); jPanel50.add(deviceWave24, java.awt.BorderLayout.CENTER); @@ -570,13 +612,13 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { deviceWave26.setUpdateExpression(""); jPanel65.add(deviceWave26, java.awt.BorderLayout.CENTER); - jTabbedPane9.addTab("RF3 Capacitance [pF]", jPanel65); + jTabbedPane9.addTab("RF3 Capacitance [nF]", jPanel65); jTabbedPane2.addTab("RF3 Setup", jTabbedPane9); jPanel66.setLayout(new java.awt.BorderLayout()); - deviceWave27.setIdentifier("rf4_power"); + deviceWave27.setIdentifier(""); deviceWave27.setOffsetNid(248); deviceWave27.setUpdateExpression(""); jPanel66.add(deviceWave27, java.awt.BorderLayout.CENTER); @@ -599,7 +641,7 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { deviceWave29.setUpdateExpression(""); jPanel68.add(deviceWave29, java.awt.BorderLayout.CENTER); - jTabbedPane10.addTab("RF4 Capacitance [pF]", jPanel68); + jTabbedPane10.addTab("RF4 Capacitance [nF]", jPanel68); jTabbedPane2.addTab("RF4 Setup", jTabbedPane10); @@ -827,10 +869,6 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { jPanel18.setLayout(new java.awt.BorderLayout()); - jPanel19.setLayout(new java.awt.BorderLayout()); - - jPanel41.setLayout(new java.awt.GridLayout(2, 0)); - jPanel20.setBorder(javax.swing.BorderFactory.createTitledBorder("Gas And Vacuum Timing")); deviceField12.setIdentifier(""); @@ -839,42 +877,27 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { deviceField12.setOffsetNid(69); jPanel20.add(deviceField12); - jPanel41.add(jPanel20); + jPanel18.add(jPanel20, java.awt.BorderLayout.NORTH); + + jPanel19.setLayout(new java.awt.BorderLayout()); + + jPanel56.setLayout(new java.awt.BorderLayout()); jPanel43.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0, 5)); jPanel42.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); deviceField40.setIdentifier(""); - deviceField40.setLabelString("Pre Set Press. [barG]:"); + deviceField40.setLabelString("GIS-B Pre Set Press. [barG]:"); deviceField40.setNumCols(5); deviceField40.setOffsetNid(320); jPanel42.add(deviceField40); jPanel43.add(jPanel42); - jPanel55.setBorder(javax.swing.BorderFactory.createTitledBorder("GVS Configuration")); - - deviceField26.setIdentifier(""); - deviceField26.setLabelString("VC3001 Turns:"); - deviceField26.setNumCols(5); - deviceField26.setOffsetNid(209); - jPanel55.add(deviceField26); - - jLabel1.setText("/25 "); - jPanel55.add(jLabel1); + jPanel55.setBorder(javax.swing.BorderFactory.createTitledBorder("GIS-B Configuration")); - deviceField27.setIdentifier(""); - deviceField27.setLabelString("VC3002 Turns: "); - deviceField27.setNumCols(5); - deviceField27.setOffsetNid(210); - jPanel55.add(deviceField27); - - jLabel2.setText("/25 "); - jLabel2.setToolTipText(""); - jPanel55.add(jLabel2); - - deviceChoice11.setChoiceItems(new String[] {"3000", "3090"}); + deviceChoice11.setChoiceItems(new String[] {"4000", "4090"}); deviceChoice11.setIdentifier(""); deviceChoice11.setLabelString("Tank"); deviceChoice11.setOffsetNid(321); @@ -890,9 +913,7 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { jPanel43.add(jPanel55); - jPanel41.add(jPanel43); - - jPanel19.add(jPanel41, java.awt.BorderLayout.NORTH); + jPanel56.add(jPanel43, java.awt.BorderLayout.NORTH); jPanel21.setLayout(new java.awt.BorderLayout()); @@ -901,7 +922,7 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { deviceWave10.setUpdateExpression(""); jPanel21.add(deviceWave10, java.awt.BorderLayout.CENTER); - jTabbedPane4.addTab("Pressure Modulation %", jPanel21); + jTabbedPane4.addTab("GIS-B Pressure Modulation %", jPanel21); jPanel22.setLayout(new java.awt.BorderLayout()); @@ -911,7 +932,7 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { deviceWave11.setUpdateExpression(""); jPanel22.add(deviceWave11, java.awt.BorderLayout.CENTER); - jTabbedPane4.addTab("VG-3011 Open(1) / Close(0) ", jPanel22); + jTabbedPane4.addTab("HVD2 VG-01 Open(1) / Close(0) ", jPanel22); jPanel23.setLayout(new java.awt.BorderLayout()); @@ -921,9 +942,140 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { deviceWave12.setUpdateExpression(""); jPanel23.add(deviceWave12, java.awt.BorderLayout.CENTER); - jTabbedPane4.addTab("VG-3012 Open(1) / Close(0) ", jPanel23); + jTabbedPane4.addTab("HVD2 VG-02 Open(1) / Close(0) ", jPanel23); + + jPanel41.setLayout(new java.awt.BorderLayout()); + + deviceWave18.setIdentifier(""); + deviceWave18.setMaxYVisible(false); + deviceWave18.setOffsetNid(89); + deviceWave18.setUpdateExpression(""); + jPanel41.add(deviceWave18, java.awt.BorderLayout.CENTER); + + jTabbedPane4.addTab("HVD2 VG-03 Open(1) / Close(0) ", jPanel41); + + jPanel75.setLayout(new java.awt.BorderLayout()); + + deviceWave19.setIdentifier(""); + deviceWave19.setMaxYVisible(false); + deviceWave19.setOffsetNid(95); + deviceWave19.setUpdateExpression(""); + jPanel75.add(deviceWave19, java.awt.BorderLayout.CENTER); + + jTabbedPane4.addTab("HVD2 VG-04 Open(1) / Close(0) ", jPanel75); + + jPanel56.add(jTabbedPane4, java.awt.BorderLayout.CENTER); + + jTabbedPane11.addTab("GIS-B Gas Injection", jPanel56); + + jPanel57.setLayout(new java.awt.BorderLayout()); + + jPanel58.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0, 5)); + + jPanel69.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); + + deviceField44.setIdentifier(""); + deviceField44.setLabelString("GIS-C Pre Set Press. [barG]:"); + deviceField44.setNumCols(5); + deviceField44.setOffsetNid(331); + jPanel69.add(deviceField44); + + jPanel58.add(jPanel69); + + jPanel70.setBorder(javax.swing.BorderFactory.createTitledBorder("GIS-C Configuration")); + jPanel70.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0, 5)); + + deviceField45.setIdentifier(""); + deviceField45.setLabelString("VC5001 Turns:"); + deviceField45.setNumCols(5); + deviceField45.setOffsetNid(209); + jPanel70.add(deviceField45); + + jLabel3.setText("/25 "); + jPanel70.add(jLabel3); + + deviceField46.setIdentifier(""); + deviceField46.setLabelString("VC5002 Turns: "); + deviceField46.setNumCols(5); + deviceField46.setOffsetNid(210); + jPanel70.add(deviceField46); + + jLabel4.setText("/25 "); + jLabel4.setToolTipText(""); + jPanel70.add(jLabel4); + + deviceField47.setIdentifier(""); + deviceField47.setLabelString("VC5003 Turns:"); + deviceField47.setNumCols(5); + deviceField47.setOffsetNid(209); + jPanel70.add(deviceField47); + + jLabel5.setText("/25 "); + jLabel5.setToolTipText(""); + jPanel70.add(jLabel5); + + deviceChoice13.setChoiceItems(new String[] {"5000", "5090"}); + deviceChoice13.setIdentifier(""); + deviceChoice13.setLabelString("Tank"); + deviceChoice13.setOffsetNid(329); + deviceChoice13.setUpdateIdentifier(""); + jPanel70.add(deviceChoice13); + + deviceChoice14.setChoiceItems(new String[] {"H2", "D2"}); + deviceChoice14.setIdentifier(""); + deviceChoice14.setLabelString("Gas Type:"); + deviceChoice14.setOffsetNid(330); + deviceChoice14.setUpdateIdentifier(""); + jPanel70.add(deviceChoice14); + + jPanel58.add(jPanel70); + + jPanel57.add(jPanel58, java.awt.BorderLayout.NORTH); + + jPanel71.setLayout(new java.awt.BorderLayout()); + + deviceWave14.setIdentifier(""); + deviceWave14.setOffsetNid(101); + deviceWave14.setUpdateExpression(""); + jPanel71.add(deviceWave14, java.awt.BorderLayout.CENTER); + + jTabbedPane12.addTab("GIS-C Pressure Modulation %", jPanel71); + + jPanel72.setLayout(new java.awt.BorderLayout()); + + deviceWave15.setIdentifier(""); + deviceWave15.setMaxYVisible(false); + deviceWave15.setOffsetNid(107); + deviceWave15.setUpdateExpression(""); + jPanel72.add(deviceWave15, java.awt.BorderLayout.CENTER); + + jTabbedPane12.addTab("VG-5011 Open(1) / Close(0) ", jPanel72); + + jPanel73.setLayout(new java.awt.BorderLayout()); + + deviceWave16.setIdentifier(""); + deviceWave16.setMaxYVisible(false); + deviceWave16.setOffsetNid(113); + deviceWave16.setUpdateExpression(""); + jPanel73.add(deviceWave16, java.awt.BorderLayout.CENTER); + + jTabbedPane12.addTab("VG-5012 Open(1) / Close(0) ", jPanel73); + + jPanel74.setLayout(new java.awt.BorderLayout()); + + deviceWave17.setIdentifier(""); + deviceWave17.setMaxYVisible(false); + deviceWave17.setOffsetNid(333); + deviceWave17.setUpdateExpression(""); + jPanel74.add(deviceWave17, java.awt.BorderLayout.CENTER); + + jTabbedPane12.addTab("VG-5013 Open(1) / Close(0) ", jPanel74); + + jPanel57.add(jTabbedPane12, java.awt.BorderLayout.CENTER); + + jTabbedPane11.addTab("GIS-C Gas Injection", jPanel57); - jPanel19.add(jTabbedPane4, java.awt.BorderLayout.CENTER); + jPanel19.add(jTabbedPane11, java.awt.BorderLayout.CENTER); jPanel18.add(jPanel19, java.awt.BorderLayout.CENTER); @@ -1023,7 +1175,10 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private DeviceChoice deviceChoice10; private DeviceChoice deviceChoice11; private DeviceChoice deviceChoice12; + private DeviceChoice deviceChoice13; + private DeviceChoice deviceChoice14; private DeviceChoice deviceChoice2; + private DeviceChoice deviceChoice3; private DeviceChoice deviceChoice4; private DeviceChoice deviceChoice5; private DeviceChoice deviceChoice6; @@ -1043,11 +1198,11 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private DeviceField deviceField19; private DeviceField deviceField2; private DeviceField deviceField20; + private DeviceField deviceField21; + private DeviceField deviceField22; private DeviceField deviceField23; private DeviceField deviceField24; private DeviceField deviceField25; - private DeviceField deviceField26; - private DeviceField deviceField27; private DeviceField deviceField28; private DeviceField deviceField29; private DeviceField deviceField3; @@ -1063,8 +1218,13 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private DeviceField deviceField39; private DeviceField deviceField4; private DeviceField deviceField40; + private DeviceField deviceField41; private DeviceField deviceField42; private DeviceField deviceField43; + private DeviceField deviceField44; + private DeviceField deviceField45; + private DeviceField deviceField46; + private DeviceField deviceField47; private DeviceField deviceField5; private DeviceField deviceField6; private DeviceField deviceField7; @@ -1076,6 +1236,11 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private DeviceWave deviceWave12; private DeviceWave deviceWave13; private DeviceWave deviceWave14; + private DeviceWave deviceWave15; + private DeviceWave deviceWave16; + private DeviceWave deviceWave17; + private DeviceWave deviceWave18; + private DeviceWave deviceWave19; private DeviceWave deviceWave2; private DeviceWave deviceWave21; private DeviceWave deviceWave22; @@ -1093,8 +1258,9 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private DeviceWave deviceWave7; private DeviceWave deviceWave8; private DeviceWave deviceWave9; - private javax.swing.JLabel jLabel1; - private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel11; @@ -1111,6 +1277,7 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private javax.swing.JPanel jPanel21; private javax.swing.JPanel jPanel22; private javax.swing.JPanel jPanel23; + private javax.swing.JPanel jPanel24; private javax.swing.JPanel jPanel25; private javax.swing.JPanel jPanel26; private javax.swing.JPanel jPanel27; @@ -1121,6 +1288,7 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private javax.swing.JPanel jPanel31; private javax.swing.JPanel jPanel32; private javax.swing.JPanel jPanel33; + private javax.swing.JPanel jPanel34; private javax.swing.JPanel jPanel35; private javax.swing.JPanel jPanel36; private javax.swing.JPanel jPanel37; @@ -1145,6 +1313,8 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private javax.swing.JPanel jPanel54; private javax.swing.JPanel jPanel55; private javax.swing.JPanel jPanel56; + private javax.swing.JPanel jPanel57; + private javax.swing.JPanel jPanel58; private javax.swing.JPanel jPanel59; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel60; @@ -1156,11 +1326,20 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private javax.swing.JPanel jPanel66; private javax.swing.JPanel jPanel67; private javax.swing.JPanel jPanel68; + private javax.swing.JPanel jPanel69; private javax.swing.JPanel jPanel7; + private javax.swing.JPanel jPanel70; + private javax.swing.JPanel jPanel71; + private javax.swing.JPanel jPanel72; + private javax.swing.JPanel jPanel73; + private javax.swing.JPanel jPanel74; + private javax.swing.JPanel jPanel75; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTabbedPane jTabbedPane10; + private javax.swing.JTabbedPane jTabbedPane11; + private javax.swing.JTabbedPane jTabbedPane12; private javax.swing.JTabbedPane jTabbedPane2; private javax.swing.JTabbedPane jTabbedPane3; private javax.swing.JTabbedPane jTabbedPane4; diff --git a/java/jdevices/src/main/java/SPIDER_SETUPSetup.java b/java/jdevices/src/main/java/SPIDER_SETUPSetup.java index d325ffbc8b..e157932468 100644 --- a/java/jdevices/src/main/java/SPIDER_SETUPSetup.java +++ b/java/jdevices/src/main/java/SPIDER_SETUPSetup.java @@ -33,6 +33,7 @@ public SPIDER_SETUPSetup() { @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents private void initComponents() { + java.awt.GridBagConstraints gridBagConstraints; deviceButtons1 = new DeviceButtons(); jTabbedPane1 = new javax.swing.JTabbedPane(); @@ -185,12 +186,90 @@ private void initComponents() { deviceWave11 = new DeviceWave(); jPanel23 = new javax.swing.JPanel(); deviceWave12 = new DeviceWave(); + jPanel24 = new javax.swing.JPanel(); + jPanel34 = new javax.swing.JPanel(); + jPanel57 = new javax.swing.JPanel(); + jPanel84 = new javax.swing.JPanel(); + jLabel3 = new javax.swing.JLabel(); + jPanel85 = new javax.swing.JPanel(); + jLabel4 = new javax.swing.JLabel(); + jPanel58 = new javax.swing.JPanel(); + jLabel6 = new javax.swing.JLabel(); + jLabel9 = new javax.swing.JLabel(); + jLabel8 = new javax.swing.JLabel(); + jLabel10 = new javax.swing.JLabel(); + jPanel69 = new javax.swing.JPanel(); + deviceField21 = new DeviceField(); + deviceField22 = new DeviceField(); + deviceField41 = new DeviceField(); + deviceField44 = new DeviceField(); + jPanel70 = new javax.swing.JPanel(); + deviceField45 = new DeviceField(); + deviceField46 = new DeviceField(); + deviceField47 = new DeviceField(); + deviceField48 = new DeviceField(); + jPanel71 = new javax.swing.JPanel(); + jLabel13 = new javax.swing.JLabel(); + jPanel72 = new javax.swing.JPanel(); + deviceField49 = new DeviceField(); + deviceField50 = new DeviceField(); + jLabel14 = new javax.swing.JLabel(); + deviceField51 = new DeviceField(); + deviceField52 = new DeviceField(); + jPanel73 = new javax.swing.JPanel(); + deviceField53 = new DeviceField(); + deviceField54 = new DeviceField(); + jLabel15 = new javax.swing.JLabel(); + deviceField55 = new DeviceField(); + deviceField56 = new DeviceField(); + jPanel74 = new javax.swing.JPanel(); + jPanel82 = new javax.swing.JPanel(); + jLabel7 = new javax.swing.JLabel(); + jPanel83 = new javax.swing.JPanel(); + jLabel17 = new javax.swing.JLabel(); + jPanel75 = new javax.swing.JPanel(); + deviceField57 = new DeviceField(); + deviceField58 = new DeviceField(); + jLabel18 = new javax.swing.JLabel(); + deviceField59 = new DeviceField(); + deviceField60 = new DeviceField(); + jPanel76 = new javax.swing.JPanel(); + deviceField61 = new DeviceField(); + deviceField62 = new DeviceField(); + jLabel24 = new javax.swing.JLabel(); + deviceField63 = new DeviceField(); + deviceField64 = new DeviceField(); + jPanel77 = new javax.swing.JPanel(); + deviceField65 = new DeviceField(); + deviceField66 = new DeviceField(); + jLabel20 = new javax.swing.JLabel(); + deviceField67 = new DeviceField(); + deviceField68 = new DeviceField(); + jPanel78 = new javax.swing.JPanel(); + deviceField69 = new DeviceField(); + deviceField70 = new DeviceField(); + jLabel21 = new javax.swing.JLabel(); + deviceField71 = new DeviceField(); + deviceField72 = new DeviceField(); + jPanel79 = new javax.swing.JPanel(); + jPanel80 = new javax.swing.JPanel(); + deviceField73 = new DeviceField(); + deviceField74 = new DeviceField(); + jLabel22 = new javax.swing.JLabel(); + deviceField75 = new DeviceField(); + deviceField76 = new DeviceField(); + jPanel81 = new javax.swing.JPanel(); + deviceField77 = new DeviceField(); + deviceField78 = new DeviceField(); + jLabel23 = new javax.swing.JLabel(); + deviceField79 = new DeviceField(); + deviceField80 = new DeviceField(); setDeviceProvider("soserver.nbtf:9000"); setDeviceTitle("SPIDER Experiment Setup"); setDeviceType("SPIDER_SETUP"); setHeight(650); - setWidth(1200); + setWidth(1000); deviceButtons1.setCheckExpressions(new String[] {}); deviceButtons1.setCheckMessages(new String[] {}); @@ -249,6 +328,11 @@ public void focusLost(java.awt.event.FocusEvent evt) { deviceField13.setLabelString("Start Time: "); deviceField13.setNumCols(30); deviceField13.setOffsetNid(122); + deviceField13.addFocusListener(new java.awt.event.FocusAdapter() { + public void focusLost(java.awt.event.FocusEvent evt) { + deviceField13FocusLost(evt); + } + }); jPanel29.add(deviceField13); deviceField17.setIdentifier(""); @@ -930,12 +1014,340 @@ public void propertyChange(java.beans.PropertyChangeEvent evt) { jTabbedPane1.addTab("GVS", jPanel18); + jPanel24.setLayout(new java.awt.BorderLayout()); + + jPanel34.setLayout(new java.awt.GridLayout(15, 0, 0, -5)); + + jPanel57.setLayout(new java.awt.GridLayout(1, 0, 0, 2)); + + jPanel84.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 20)); + + jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N + jLabel3.setText("AGPS"); + jPanel84.add(jLabel3); + + jPanel57.add(jPanel84); + + jPanel85.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 20)); + + jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N + jLabel4.setText("GVS"); + jPanel85.add(jLabel4); + + jPanel57.add(jPanel85); + + jPanel34.add(jPanel57); + + java.awt.GridBagLayout jPanel58Layout = new java.awt.GridBagLayout(); + jPanel58Layout.columnWeights = new double[] {0.4, 0.2, 0.3, 0.2}; + jPanel58.setLayout(jPanel58Layout); + + jLabel6.setText("Session Limits"); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; + jPanel58.add(jLabel6, gridBagConstraints); + + jLabel9.setText(" Nominal Limit"); + jPanel58.add(jLabel9, new java.awt.GridBagConstraints()); + + jLabel8.setText("Session Limits"); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; + jPanel58.add(jLabel8, gridBagConstraints); + + jLabel10.setText(" Nominal Limit"); + jPanel58.add(jLabel10, new java.awt.GridBagConstraints()); + + jPanel34.add(jPanel58); + + java.awt.GridBagLayout jPanel69Layout = new java.awt.GridBagLayout(); + jPanel69Layout.columnWeights = new double[] {0.4, 0.2, 0.4, 0.2}; + jPanel69.setLayout(jPanel69Layout); + + deviceField21.setEditable(false); + deviceField21.setIdentifier(""); + deviceField21.setLabelString("Output Voltage [kV] (Plasma)"); + deviceField21.setOffsetNid(330); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; + jPanel69.add(deviceField21, gridBagConstraints); + + deviceField22.setEditable(false); + deviceField22.setIdentifier(""); + deviceField22.setOffsetNid(352); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; + jPanel69.add(deviceField22, gridBagConstraints); + + deviceField41.setEditable(false); + deviceField41.setLabelString("Preset Pressure (min) [BarG]"); + deviceField41.setOffsetNid(331); + jPanel69.add(deviceField41, new java.awt.GridBagConstraints()); + + deviceField44.setEditable(false); + deviceField44.setOffsetNid(353); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE; + gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; + jPanel69.add(deviceField44, gridBagConstraints); + + jPanel34.add(jPanel69); + + java.awt.GridBagLayout jPanel70Layout = new java.awt.GridBagLayout(); + jPanel70Layout.columnWeights = new double[] {0.4, 0.2, 0.4, 0.2}; + jPanel70.setLayout(jPanel70Layout); + + deviceField45.setEditable(false); + deviceField45.setIdentifier(""); + deviceField45.setLabelString("Output Voltage [kV] (Vacuum)"); + deviceField45.setOffsetNid(346); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; + jPanel70.add(deviceField45, gridBagConstraints); + + deviceField46.setEditable(false); + deviceField46.setIdentifier(""); + deviceField46.setOffsetNid(368); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; + jPanel70.add(deviceField46, gridBagConstraints); + + deviceField47.setEditable(false); + deviceField47.setLabelString("Preset Pressure (max) [BarG]"); + deviceField47.setOffsetNid(332); + jPanel70.add(deviceField47, new java.awt.GridBagConstraints()); + + deviceField48.setEditable(false); + deviceField48.setIdentifier(""); + deviceField48.setOffsetNid(354); + gridBagConstraints = new java.awt.GridBagConstraints(); + gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; + jPanel70.add(deviceField48, gridBagConstraints); + + jPanel34.add(jPanel70); + + jPanel71.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 15)); + + jLabel13.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N + jLabel13.setText("---------------------------- ISEPS ---------------------------"); + jPanel71.add(jLabel13); + + jPanel34.add(jPanel71); + + deviceField49.setEditable(false); + deviceField49.setLabelString("ISEG Output Voltage [V] "); + deviceField49.setOffsetNid(333); + jPanel72.add(deviceField49); + + deviceField50.setEditable(false); + deviceField50.setOffsetNid(355); + jPanel72.add(deviceField50); + + jLabel14.setText(" "); + jPanel72.add(jLabel14); + + deviceField51.setEditable(false); + deviceField51.setLabelString("ISSS Output Current [A]"); + deviceField51.setOffsetNid(335); + jPanel72.add(deviceField51); + + deviceField52.setEditable(false); + deviceField52.setOffsetNid(357); + jPanel72.add(deviceField52); + + jPanel34.add(jPanel72); + + deviceField53.setEditable(false); + deviceField53.setLabelString("ISRF-TE Output Voltage [V]"); + deviceField53.setOffsetNid(334); + jPanel73.add(deviceField53); + + deviceField54.setEditable(false); + deviceField54.setOffsetNid(356); + jPanel73.add(deviceField54); + + jLabel15.setText(" "); + jPanel73.add(jLabel15); + + deviceField55.setEditable(false); + deviceField55.setLabelString("ISPG Output Current [A]"); + deviceField55.setOffsetNid(336); + jPanel73.add(deviceField55); + + deviceField56.setEditable(false); + deviceField56.setOffsetNid(358); + jPanel73.add(deviceField56); + + jPanel34.add(jPanel73); + + jPanel74.setLayout(new java.awt.GridLayout(1, 0, 0, 2)); + + jPanel82.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 20)); + + jLabel7.setText(" Vacuum"); + jPanel82.add(jLabel7); + + jPanel74.add(jPanel82); + + jPanel83.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 20)); + + jLabel17.setText(" With Plasma"); + jPanel83.add(jLabel17); + + jPanel74.add(jPanel83); + + jPanel34.add(jPanel74); + + deviceField57.setEditable(false); + deviceField57.setIdentifier(""); + deviceField57.setLabelString("ISRF1 - Output Power [kV] "); + deviceField57.setOffsetNid(347); + jPanel75.add(deviceField57); + + deviceField58.setEditable(false); + deviceField58.setOffsetNid(369); + jPanel75.add(deviceField58); + + jLabel18.setText(" "); + jPanel75.add(jLabel18); + + deviceField59.setEditable(false); + deviceField59.setLabelString("ISRF1 - Output Power [kV] "); + deviceField59.setOffsetNid(337); + jPanel75.add(deviceField59); + + deviceField60.setEditable(false); + deviceField60.setOffsetNid(359); + jPanel75.add(deviceField60); + + jPanel34.add(jPanel75); + + deviceField61.setEditable(false); + deviceField61.setLabelString("ISRF2 - Output Power [kV] "); + deviceField61.setOffsetNid(348); + jPanel76.add(deviceField61); + + deviceField62.setEditable(false); + deviceField62.setOffsetNid(370); + jPanel76.add(deviceField62); + + jLabel24.setText(" "); + jPanel76.add(jLabel24); + + deviceField63.setEditable(false); + deviceField63.setLabelString("ISRF2 - Output Power [kV] "); + deviceField63.setOffsetNid(338); + jPanel76.add(deviceField63); + + deviceField64.setEditable(false); + deviceField64.setOffsetNid(360); + jPanel76.add(deviceField64); + + jPanel34.add(jPanel76); + + deviceField65.setEditable(false); + deviceField65.setLabelString("ISRF3 - Output Power [kV] "); + deviceField65.setOffsetNid(349); + jPanel77.add(deviceField65); + + deviceField66.setEditable(false); + deviceField66.setOffsetNid(371); + jPanel77.add(deviceField66); + + jLabel20.setText(" "); + jPanel77.add(jLabel20); + + deviceField67.setEditable(false); + deviceField67.setLabelString("ISRF3 - Output Power [kV] "); + deviceField67.setOffsetNid(339); + jPanel77.add(deviceField67); + + deviceField68.setEditable(false); + deviceField68.setOffsetNid(361); + jPanel77.add(deviceField68); + + jPanel34.add(jPanel77); + + deviceField69.setEditable(false); + deviceField69.setLabelString("ISRF4 - Output Power [kV] "); + deviceField69.setOffsetNid(350); + jPanel78.add(deviceField69); + + deviceField70.setEditable(false); + deviceField70.setOffsetNid(372); + jPanel78.add(deviceField70); + + jLabel21.setText(" "); + jPanel78.add(jLabel21); + + deviceField71.setEditable(false); + deviceField71.setLabelString("ISRF4 - Output Power [kV] "); + deviceField71.setOffsetNid(340); + jPanel78.add(deviceField71); + + deviceField72.setEditable(false); + deviceField72.setOffsetNid(362); + jPanel78.add(deviceField72); + + jPanel34.add(jPanel78); + jPanel34.add(jPanel79); + + deviceField73.setEditable(false); + deviceField73.setLabelString("ISBI - Output Voltage [V] "); + deviceField73.setOffsetNid(341); + jPanel80.add(deviceField73); + + deviceField74.setEditable(false); + deviceField74.setOffsetNid(363); + jPanel80.add(deviceField74); + + jLabel22.setText(" "); + jPanel80.add(jLabel22); + + deviceField75.setEditable(false); + deviceField75.setLabelString("ISBI - Output Current [A]"); + deviceField75.setOffsetNid(343); + jPanel80.add(deviceField75); + + deviceField76.setEditable(false); + deviceField76.setOffsetNid(365); + jPanel80.add(deviceField76); + + jPanel34.add(jPanel80); + + deviceField77.setEditable(false); + deviceField77.setLabelString("ISBP - Output Voltage [V]"); + deviceField77.setOffsetNid(342); + jPanel81.add(deviceField77); + + deviceField78.setEditable(false); + deviceField78.setOffsetNid(364); + jPanel81.add(deviceField78); + + jLabel23.setText(" ' "); + jPanel81.add(jLabel23); + + deviceField79.setEditable(false); + deviceField79.setLabelString("ISBP - Output Current [A]"); + deviceField79.setOffsetNid(344); + jPanel81.add(deviceField79); + + deviceField80.setEditable(false); + deviceField80.setIdentifier(""); + deviceField80.setOffsetNid(366); + jPanel81.add(deviceField80); + + jPanel34.add(jPanel81); + + jPanel24.add(jPanel34, java.awt.BorderLayout.CENTER); + + jTabbedPane1.addTab("Safety Parameters - Annex B", jPanel24); + getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER); }// //GEN-END:initComponents private void deviceField17PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_deviceField17PropertyChange // TODO add your handling code here: - //updateWaves(); }//GEN-LAST:event_deviceField17PropertyChange @@ -943,24 +1355,24 @@ private void updateWaves() { float maxX = 0, minX = 0; try { - //MDSplus.Data data = (MDSplus.Data)this.deviceField13.getData(); + //Data data = this.deviceField13.getData(); //minX = (subtree.evaluateData(subtree.dataFromExpr("FLOAT(" + subtree.dataToString(data) + ")"), 0)).getFloat(); minX = subtree.getFloat(this.deviceField13.getData()); } catch (Exception ex) { JOptionPane.showMessageDialog(SPIDER_SETUPSetup.this, "The value on the file Start Time in the Reference Wave Time Limit pannel isn't a valid float value or mdsplus expression.", - "Incorret Start Time Reference wave limits ", JOptionPane.WARNING_MESSAGE); + "Incorret Start Time Reference wave limits", JOptionPane.WARNING_MESSAGE); return; } try { - //MDSplus.Data data = (MDSplus.Data)this.deviceField17.getFullData(); + //Data data = this.deviceField17.getData(); //maxX = (subtree.evaluateData(subtree.dataFromExpr("FLOAT(" + subtree.dataToString(data) + ")"), 0)).getFloat(); - maxX = subtree.getFloat(this.deviceField17.getData()); + maxX = subtree.getFloat(this.deviceField17.getData()); } catch (Exception ex) { JOptionPane.showMessageDialog(SPIDER_SETUPSetup.this, - "The value on the file Stop Time in the Reference Wave Time Limit pannel isn't a valid float value or mdsplus expression.\n"+ex, - "Incorret Start Time Reference wave limits ", JOptionPane.WARNING_MESSAGE); + "The value on the file Stop Time in the Reference Wave Time Limit pannel isn't a valid float value or mdsplus expression.", + "Incorret Start Time Reference wave limits", JOptionPane.WARNING_MESSAGE); return; } @@ -987,7 +1399,7 @@ private void updateWaves() deviceWave11.updateXLimit(minX, maxX); deviceWave12.updateXLimit(minX, maxX); deviceWave13.updateXLimit(minX, maxX); - deviceWave14.updateXLimit(minX, maxX); + deviceWave14.updateXLimit(minX, maxX); //deviceWave21.updateXLimit(minX, maxX); Reconnect Wave x limit fixed from 0 to 1 deviceWave22.updateXLimit(minX, maxX); deviceWave23.updateXLimit(minX, maxX); @@ -1001,21 +1413,26 @@ private void updateWaves() private void deviceField17FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_deviceField17FocusLost // TODO add your handling code here: - //System.out.println("deviceField17FocusLost"); - //updateWaves(); + System.out.println("FOCUS Lost deviceField17"); + updateWaves(); }//GEN-LAST:event_deviceField17FocusLost private void jTabbedPane1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTabbedPane1FocusLost // TODO add your handling code here: - //System.out.println("jTabbedPane1FocusLost"); - //updateWaves(); + updateWaves(); }//GEN-LAST:event_jTabbedPane1FocusLost - private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { - System.out.println("jPanel29FocusLost"); - updateWaves(); + private void deviceField13FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_deviceField13FocusLost + // TODO add your handling code here: + System.out.println("FOCUS Lost deviceField13"); + updateWaves(); + }//GEN-LAST:event_deviceField13FocusLost + + private void jPanel29FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jPanel29FocusLost // TODO add your handling code here: - } + System.out.println("FOCUS Lost jPanel29"); + updateWaves(); + }//GEN-LAST:event_jPanel29FocusLost // Variables declaration - do not modify//GEN-BEGIN:variables @@ -1044,6 +1461,8 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private DeviceField deviceField19; private DeviceField deviceField2; private DeviceField deviceField20; + private DeviceField deviceField21; + private DeviceField deviceField22; private DeviceField deviceField23; private DeviceField deviceField24; private DeviceField deviceField25; @@ -1064,12 +1483,50 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private DeviceField deviceField39; private DeviceField deviceField4; private DeviceField deviceField40; + private DeviceField deviceField41; private DeviceField deviceField42; private DeviceField deviceField43; + private DeviceField deviceField44; + private DeviceField deviceField45; + private DeviceField deviceField46; + private DeviceField deviceField47; + private DeviceField deviceField48; + private DeviceField deviceField49; private DeviceField deviceField5; + private DeviceField deviceField50; + private DeviceField deviceField51; + private DeviceField deviceField52; + private DeviceField deviceField53; + private DeviceField deviceField54; + private DeviceField deviceField55; + private DeviceField deviceField56; + private DeviceField deviceField57; + private DeviceField deviceField58; + private DeviceField deviceField59; private DeviceField deviceField6; + private DeviceField deviceField60; + private DeviceField deviceField61; + private DeviceField deviceField62; + private DeviceField deviceField63; + private DeviceField deviceField64; + private DeviceField deviceField65; + private DeviceField deviceField66; + private DeviceField deviceField67; + private DeviceField deviceField68; + private DeviceField deviceField69; private DeviceField deviceField7; + private DeviceField deviceField70; + private DeviceField deviceField71; + private DeviceField deviceField72; + private DeviceField deviceField73; + private DeviceField deviceField74; + private DeviceField deviceField75; + private DeviceField deviceField76; + private DeviceField deviceField77; + private DeviceField deviceField78; + private DeviceField deviceField79; private DeviceField deviceField8; + private DeviceField deviceField80; private DeviceField deviceField9; private DeviceWave deviceWave1; private DeviceWave deviceWave10; @@ -1095,7 +1552,24 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private DeviceWave deviceWave8; private DeviceWave deviceWave9; private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel10; + private javax.swing.JLabel jLabel13; + private javax.swing.JLabel jLabel14; + private javax.swing.JLabel jLabel15; + private javax.swing.JLabel jLabel17; + private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel20; + private javax.swing.JLabel jLabel21; + private javax.swing.JLabel jLabel22; + private javax.swing.JLabel jLabel23; + private javax.swing.JLabel jLabel24; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel6; + private javax.swing.JLabel jLabel7; + private javax.swing.JLabel jLabel8; + private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel11; @@ -1112,6 +1586,7 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private javax.swing.JPanel jPanel21; private javax.swing.JPanel jPanel22; private javax.swing.JPanel jPanel23; + private javax.swing.JPanel jPanel24; private javax.swing.JPanel jPanel25; private javax.swing.JPanel jPanel26; private javax.swing.JPanel jPanel27; @@ -1122,6 +1597,7 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private javax.swing.JPanel jPanel31; private javax.swing.JPanel jPanel32; private javax.swing.JPanel jPanel33; + private javax.swing.JPanel jPanel34; private javax.swing.JPanel jPanel35; private javax.swing.JPanel jPanel36; private javax.swing.JPanel jPanel37; @@ -1146,6 +1622,8 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private javax.swing.JPanel jPanel54; private javax.swing.JPanel jPanel55; private javax.swing.JPanel jPanel56; + private javax.swing.JPanel jPanel57; + private javax.swing.JPanel jPanel58; private javax.swing.JPanel jPanel59; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel60; @@ -1157,8 +1635,25 @@ private void jPanel29FocusLost(java.awt.event.FocusEvent evt) { private javax.swing.JPanel jPanel66; private javax.swing.JPanel jPanel67; private javax.swing.JPanel jPanel68; + private javax.swing.JPanel jPanel69; private javax.swing.JPanel jPanel7; + private javax.swing.JPanel jPanel70; + private javax.swing.JPanel jPanel71; + private javax.swing.JPanel jPanel72; + private javax.swing.JPanel jPanel73; + private javax.swing.JPanel jPanel74; + private javax.swing.JPanel jPanel75; + private javax.swing.JPanel jPanel76; + private javax.swing.JPanel jPanel77; + private javax.swing.JPanel jPanel78; + private javax.swing.JPanel jPanel79; private javax.swing.JPanel jPanel8; + private javax.swing.JPanel jPanel80; + private javax.swing.JPanel jPanel81; + private javax.swing.JPanel jPanel82; + private javax.swing.JPanel jPanel83; + private javax.swing.JPanel jPanel84; + private javax.swing.JPanel jPanel85; private javax.swing.JPanel jPanel9; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTabbedPane jTabbedPane10; diff --git a/java/jdevices/src/main/resources/BCM_CONFIGSetup.form b/java/jdevices/src/main/resources/BCM_CONFIGSetup.form new file mode 100644 index 0000000000..b93446ffad --- /dev/null +++ b/java/jdevices/src/main/resources/BCM_CONFIGSetup.form @@ -0,0 +1,274 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/jdevices/src/main/resources/DTACQ_SUPERVISORSetup.form b/java/jdevices/src/main/resources/DTACQ_SUPERVISORSetup.form index dd2d4570c1..eb4f2c7464 100644 --- a/java/jdevices/src/main/resources/DTACQ_SUPERVISORSetup.form +++ b/java/jdevices/src/main/resources/DTACQ_SUPERVISORSetup.form @@ -388,6 +388,326 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/jdevices/src/main/resources/MITICA_SETUPSetup.form b/java/jdevices/src/main/resources/MITICA_SETUPSetup.form index 81f3f055a3..39c69a6de1 100644 --- a/java/jdevices/src/main/resources/MITICA_SETUPSetup.form +++ b/java/jdevices/src/main/resources/MITICA_SETUPSetup.form @@ -1,1915 +1,1915 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/jdevices/src/main/resources/SPIDER_SETUPSetup.form b/java/jdevices/src/main/resources/SPIDER_SETUPSetup.form index 63c0a93e73..7e8ce4f92a 100644 --- a/java/jdevices/src/main/resources/SPIDER_SETUPSetup.form +++ b/java/jdevices/src/main/resources/SPIDER_SETUPSetup.form @@ -2,7 +2,7 @@
- + @@ -21,12 +21,20 @@ - + + + + + + + + + @@ -34,6 +42,9 @@ + + + @@ -131,6 +142,9 @@ + + + @@ -141,6 +155,9 @@ + + + @@ -149,6 +166,10 @@ + + + + @@ -260,48 +281,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -311,42 +291,94 @@ - + - + - - + + - - + + - + - - - + + - + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -733,6 +765,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -757,7 +816,7 @@ - + @@ -851,7 +910,7 @@ - + @@ -945,7 +1004,7 @@ - + @@ -1039,7 +1098,7 @@ - + @@ -1641,38 +1700,90 @@ - + + + + + + + + + + + + + + + + + + + + + + + + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1779,6 +1890,1166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/jdispatcher/src/main/java/mds/jdispatcher/MdsHelper.java b/java/jdispatcher/src/main/java/mds/jdispatcher/MdsHelper.java index 92d61b4d44..b137506780 100644 --- a/java/jdispatcher/src/main/java/mds/jdispatcher/MdsHelper.java +++ b/java/jdispatcher/src/main/java/mds/jdispatcher/MdsHelper.java @@ -64,12 +64,16 @@ public static Vector getServers() final Vector servers = new Vector<>(); for (int i = 1;; i++) { - final String server_class = properties.getProperty(String.format(SERVER_FMRT, i, "class")); - if (server_class == null) + String prop = properties.getProperty(String.format(SERVER_FMRT, i, "class")); + if (prop == null) break; - final String server_ip = properties.getProperty(String.format(SERVER_FMRT, i, "address")); - if (server_ip == null) + final String server_class = prop.trim(); + + prop = properties.getProperty(String.format(SERVER_FMRT, i, "address")); + if (prop == null) break; + final String server_ip = prop.trim(); + final String server_subtree = properties.getProperty(String.format(SERVER_FMRT, i, "subtree")); final String javasvr = properties.getProperty(String.format(SERVER_FMRT, i, "use_jserver")); final boolean useJavaServer = javasvr == null || javasvr.equals("true"); @@ -84,8 +88,12 @@ public static Vector getServers() } final String startScript = properties.getProperty(String.format(SERVER_FMRT, i, "start_script")); final String stopScript = properties.getProperty(String.format(SERVER_FMRT, i, "stop_script")); + + final String showtermScript = properties.getProperty(String.format(SERVER_FMRT, i, "showterm_script")); + final String showlogScript = properties.getProperty(String.format(SERVER_FMRT, i, "showlog_script")); + final ServerInfo srvInfo = new ServerInfo(server_class, server_ip, server_subtree, useJavaServer, - watchdogPort, startScript, stopScript); + watchdogPort, startScript, stopScript, showtermScript, showlogScript); servers.add(srvInfo); } return servers; diff --git a/java/jdispatcher/src/main/java/mds/jdispatcher/ServerInfo.java b/java/jdispatcher/src/main/java/mds/jdispatcher/ServerInfo.java index b4d7dc1173..b7d955c626 100644 --- a/java/jdispatcher/src/main/java/mds/jdispatcher/ServerInfo.java +++ b/java/jdispatcher/src/main/java/mds/jdispatcher/ServerInfo.java @@ -60,6 +60,57 @@ else if (si.address.startsWith("localhost:")) } } + private static void showtermServer(ServerInfo si) throws NoSuchFieldException + { + try + { + if (si.server != null) + return; + if (si.getShowtermScript() != null) + { + // final Process p = + Runtime.getRuntime().exec(si.getShowtermScript()); + // p could be logged here + } + else + { + final String msg = "For server class "+ si.getClassName() +" the showterm_script property value is undefined in properties file"; + System.out.println(msg); + throw new NoSuchFieldException(msg); + } + } + catch (final Exception exc) + { + System.out.println("For server class "+ si.getClassName() + " exception in show terminal " + exc); + } + } + + private static void showlogServer(ServerInfo si) throws NoSuchFieldException + { + try + { + if (si.server != null) + return; + if (si.getShowlogScript() != null) + { + // final Process p = + Runtime.getRuntime().exec(si.getShowlogScript()); + // p could be logged here + } + else + { + final String msg = "For server class "+ si.getClassName() +" showlog_script property value is undefined in properties file"; + System.out.println(msg); + throw new NoSuchFieldException(msg); + } + } + catch (final IOException exc) + { + System.out.println("For server class "+ si.getClassName() + " exception in show log file " + exc); + } + } + + private final String className; private final String address; private final String subTree; @@ -67,6 +118,8 @@ else if (si.address.startsWith("localhost:")) private final int watchdogPort; private final String startScript; private final String stopScript; + private final String showtermScript; + private final String showlogScript; private MdsMonitorEvent monitorEvent; private int pos; boolean killed = false; @@ -74,7 +127,7 @@ else if (si.address.startsWith("localhost:")) private boolean active; public ServerInfo(String className, String address, String subTree, boolean isJava, int watchdogPort, - String startScript, String stopScript) + String startScript, String stopScript, String showtermScript, String showlogScript) { this.active = false; this.className = className; @@ -84,6 +137,8 @@ public ServerInfo(String className, String address, String subTree, boolean isJa this.watchdogPort = watchdogPort; this.startScript = startScript; this.stopScript = stopScript; + this.showtermScript = showtermScript; + this.showlogScript = showlogScript; } public MdsMonitorEvent getAction() @@ -139,6 +194,12 @@ public String getStartScript() public String getStopScript() { return stopScript; } + public String getShowtermScript() + { return showtermScript; } + + public String getShowlogScript() + { return showlogScript; } + public String getSubTree() { return subTree; } @@ -174,6 +235,17 @@ public void stopServer() stopServer(this); } + public void showtermServer() throws NoSuchFieldException + { + showtermServer(this); + } + + public void showlogServer() throws NoSuchFieldException + { + showlogServer(this); + } + + public void stopServer(ServerInfo si) { try @@ -200,6 +272,7 @@ public String toString() { return "Class :" + className + "\n" + "Address : " + address + "\n" + "Sub Tree : " + subTree + "\n" + "Java Server : " + isJava + "\n" + "Watchdog port : " + watchdogPort + "\n" + "Start Script : " - + startScript + "\n" + "Stop Script : " + stopScript + "\n"; + + startScript + "\n" + "Stop Script : " + stopScript + "\n" + + "Open Term Script : " + showtermScript + "\n" + "Open Log Script : " + showlogScript + "\n"; } }// End ServerInfo class diff --git a/java/jdispatcher/src/main/java/mds/jdispatcher/ServersInfoPanel.java b/java/jdispatcher/src/main/java/mds/jdispatcher/ServersInfoPanel.java index 3af267fa2a..5dbaa94618 100644 --- a/java/jdispatcher/src/main/java/mds/jdispatcher/ServersInfoPanel.java +++ b/java/jdispatcher/src/main/java/mds/jdispatcher/ServersInfoPanel.java @@ -156,6 +156,9 @@ public Component getTableCellRendererComponent(final JTable table, final Object private javax.swing.JButton startAllServer; private javax.swing.JMenuItem startServer; private javax.swing.JMenuItem stopServer; + private javax.swing.JMenuItem showtermServer; + private javax.swing.JMenuItem showlogServer; + private javax.swing.JButton update; // End of variables declaration @@ -185,6 +188,7 @@ private void initComponents() jPanel2 = new JPanel(); jScrollPane1 = new JScrollPane(); jTable1 = new JTable(); + startServer = new JMenuItem("Start"); startServer.addActionListener(new java.awt.event.ActionListener() { @@ -200,6 +204,7 @@ public void actionPerformed(final ActionEvent evt) } }); serverActionPopup.add(startServer); + stopServer = new JMenuItem("Stop"); stopServer.addActionListener(new java.awt.event.ActionListener() { @@ -215,6 +220,57 @@ public void actionPerformed(final java.awt.event.ActionEvent evt) } }); serverActionPopup.add(stopServer); + + showtermServer = new JMenuItem("Show terminal"); + showtermServer.addActionListener(new java.awt.event.ActionListener() + { + @Override + public void actionPerformed(final java.awt.event.ActionEvent evt) + { + final TableModel tm = jTable1.getModel(); + String msg =""; + for (final int i : jTable1.getSelectedRows()) + { + final String s = (String) tm.getValueAt(i, 2); + try { + serversInfo.get(s).showtermServer(); + Thread.sleep(3000); + } catch (final Exception exc) { + msg = msg +"\n"+ exc; + } + } + if ( msg.length() > 0 ) + JOptionPane.showMessageDialog(ServersInfoPanel.this, msg, "Alert", JOptionPane.ERROR_MESSAGE); + + } + }); + serverActionPopup.add(showtermServer); + + showlogServer = new JMenuItem("Show log"); + showlogServer.addActionListener(new java.awt.event.ActionListener() + { + @Override + public void actionPerformed(final java.awt.event.ActionEvent evt) + { + final TableModel tm = jTable1.getModel(); + String msg =""; + for (final int i : jTable1.getSelectedRows()) + { + final String s = (String) tm.getValueAt(i, 2); + try { + serversInfo.get(s).showlogServer(); + } catch (final Exception exc) { + msg = msg +"\n"+ exc; + } + } + if ( msg.length() > 0 ) + JOptionPane.showMessageDialog(ServersInfoPanel.this, msg, "Alert", JOptionPane.ERROR_MESSAGE); + + } + }); + serverActionPopup.add(showlogServer); + + update.setText("Servers State Update"); update.addActionListener(new java.awt.event.ActionListener() { diff --git a/java/jscope/src/main/java/mds/wave/Grid.java b/java/jscope/src/main/java/mds/wave/Grid.java index 9f969fb3af..8f27f9757e 100644 --- a/java/jscope/src/main/java/mds/wave/Grid.java +++ b/java/jscope/src/main/java/mds/wave/Grid.java @@ -353,6 +353,7 @@ public void paint(Graphics g, Dimension d, Waveform w, WaveformMetrics wm) df.setTimeZone(new SimpleTimeZone(0, "GMT")); dfSubSec.setTimeZone(new SimpleTimeZone(0, "GMT")); } + final Date date = new Date(); date.setTime(datel); currStringSubSec = dfSubSec.format(date); @@ -473,6 +474,13 @@ private long toMillis(double xin) { if (xin > 2E13) xin = xin / 1E6; + + if( Waveform.timeMode == Waveform.EPICS_TIME ) + xin = xin + Waveform.EPICS_BASE; + + if( Waveform.timeMode == Waveform.VMS_TIME ) + xin = xin - Waveform.VMS_BASE/10000L; + return (long) xin; } diff --git a/java/jscope/src/main/java/mds/wave/MultiWaveform.java b/java/jscope/src/main/java/mds/wave/MultiWaveform.java index 3977b29385..ef2069b382 100644 --- a/java/jscope/src/main/java/mds/wave/MultiWaveform.java +++ b/java/jscope/src/main/java/mds/wave/MultiWaveform.java @@ -859,7 +859,7 @@ protected void NotifyZoom(double start_xs, double end_xs, double start_ys, doubl } @Override - synchronized public void paint(Graphics g, Dimension d, int print_mode) + public void paint(Graphics g, Dimension d, int print_mode) { bottom_size = right_size = 0; if (fixed_legend && show_legend || (print_mode & PRINT_LEGEND) == PRINT_LEGEND) diff --git a/java/jscope/src/main/java/mds/wave/WaveInterface.java b/java/jscope/src/main/java/mds/wave/WaveInterface.java index 1494a66b13..f5321aac75 100644 --- a/java/jscope/src/main/java/mds/wave/WaveInterface.java +++ b/java/jscope/src/main/java/mds/wave/WaveInterface.java @@ -522,7 +522,7 @@ public synchronized void EvaluateShot(long shot) throws Exception w_error[curr_wave] = null; try { - signals[curr_wave] = GetSignal(curr_wave, -Double.MAX_VALUE, Double.MAX_VALUE); + signals[curr_wave] = GetSignal(curr_wave, xmin, xmax); evaluated[curr_wave] = true; } catch (final Exception exc) diff --git a/java/jscope/src/main/java/mds/wave/Waveform.java b/java/jscope/src/main/java/mds/wave/Waveform.java index 60ca7ba814..d23eea7299 100644 --- a/java/jscope/src/main/java/mds/wave/Waveform.java +++ b/java/jscope/src/main/java/mds/wave/Waveform.java @@ -1305,7 +1305,7 @@ protected double MinYSignal() protected void NotifyZoom(double start_xs, double end_xs, double start_ys, double end_ys, int timestamp) {} - synchronized public void paint(Graphics g, Dimension d, int print_mode) + public void paint(Graphics g, Dimension d, int print_mode) { execute_print = (print_mode != NO_PRINT); final Insets i = this.getInsets(); diff --git a/java/jtraverser/src/main/java/mds/jtraverser/Database.java b/java/jtraverser/src/main/java/mds/jtraverser/Database.java index d5b2200cfb..04ac3b0368 100644 --- a/java/jtraverser/src/main/java/mds/jtraverser/Database.java +++ b/java/jtraverser/src/main/java/mds/jtraverser/Database.java @@ -159,7 +159,7 @@ public NodeInfo getInfo(int nid) throws Exception cal.setTimeInMillis(time); final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss"); final String dateStr = sdf.format(cal); - return new NodeInfo(node.getDclass(), node.getDtype(), node.getUsage(), node.getFlags(), node.getOwnerId(), + return new NodeInfo(node.getDclass(), node.getDtype(), node.getUsage(), node.getFlags(), node.getOwnerId(), node.getLength(), node.getConglomerateNodes().size(), node.getConglomerateElt(), dateStr, node.getNodeName(), node.getFullPath(), node.getMinPath(), node.getPath(), node.getNumSegments()); } diff --git a/java/jtraverser/src/main/java/mds/jtraverser/Node.java b/java/jtraverser/src/main/java/mds/jtraverser/Node.java index dce9542ade..43265f4f8f 100644 --- a/java/jtraverser/src/main/java/mds/jtraverser/Node.java +++ b/java/jtraverser/src/main/java/mds/jtraverser/Node.java @@ -429,7 +429,7 @@ private static ImageIcon ICON_LOADER(String gifname) ICONS.put("ACTION", ICON_LOADER("action")); ICONS.put("DEVICE", ICON_LOADER("device")); ICONS.put("DISPATCH", ICON_LOADER("dispatch")); - ICONS.put("ANY", ICON_NUMERIC); + ICONS.put("ANY", ICON_LOADER("any")); ICONS.put("NUMERIC", ICON_NUMERIC); ICONS.put("TASK", ICON_LOADER("task")); ICONS.put("TEXT", ICON_LOADER("text")); diff --git a/java/jtraverser/src/main/java/mds/jtraverser/Tree.java b/java/jtraverser/src/main/java/mds/jtraverser/Tree.java index 360a1a0fe9..a72d37e8dc 100644 --- a/java/jtraverser/src/main/java/mds/jtraverser/Tree.java +++ b/java/jtraverser/src/main/java/mds/jtraverser/Tree.java @@ -630,7 +630,7 @@ public static final void setCurrentNode(final Node curr_node) private JTextField add_device_type, add_device_name; private String lastName; // Temporary, to overcome Java's bugs on inner classes - JMenuItem add_action_b, add_dispatch_b, add_numeric_b, add_signal_b, add_task_b, add_text_b, add_window_b, + JMenuItem add_action_b, add_dispatch_b, add_numeric_b, add_signal_b, add_any_b, add_task_b, add_text_b, add_window_b, add_axis_b, add_device_b, add_child_b, add_subtree_b, delete_node_b, modify_tags_b; JButton ok_cb, add_node_ok; @@ -676,6 +676,8 @@ public void actionPerformed(ActionEvent e) addNode("NUMERIC"); if (jb == add_signal_b) addNode("SIGNAL"); + if (jb == add_any_b) + addNode("ANY"); if (jb == add_task_b) addNode("TASK"); if (jb == add_text_b) @@ -1216,6 +1218,8 @@ public void mousePressed(MouseEvent e) add_numeric_b.addActionListener(this); jm.add(add_signal_b = new JMenuItem("Signal")); add_signal_b.addActionListener(this); + jm.add(add_any_b = new JMenuItem("Any")); + add_any_b.addActionListener(this); jm.add(add_task_b = new JMenuItem("Task")); add_task_b.addActionListener(this); jm.add(add_text_b = new JMenuItem("Text")); diff --git a/java/jtraverser/src/main/java/mds/jtraverser/jTraverser.java b/java/jtraverser/src/main/java/mds/jtraverser/jTraverser.java index b2d3eedf3a..c506d336f5 100644 --- a/java/jtraverser/src/main/java/mds/jtraverser/jTraverser.java +++ b/java/jtraverser/src/main/java/mds/jtraverser/jTraverser.java @@ -44,7 +44,7 @@ public static void stdout(String line) JMenu file_m, edit_m, data_m, customize_m; JMenuItem open, close, quit; - JMenuItem add_action_b, add_dispatch_b, add_numeric_b, add_signal_b, add_task_b, add_text_b, add_window_b, + JMenuItem add_action_b, add_dispatch_b, add_numeric_b, add_signal_b, add_any_b, add_task_b, add_text_b, add_window_b, add_axis_b, add_device_b, add_child_b, add_subtree_b, delete_node_b, modify_tags_b, rename_node_b, turn_on_b, turn_off_b, display_data_b, display_nci_b, display_tags_b, modify_data_b, set_default_b, setup_device_b, do_action_b, outline_b, tree_b, copy_b, paste_b; @@ -95,6 +95,8 @@ public jTraverser(String exp_name, String shot_name, String access) add_numeric_b.addActionListener(this); jm.add(add_signal_b = new JMenuItem("Signal")); add_signal_b.addActionListener(this); + jm.add(add_any_b = new JMenuItem("Any")); + add_any_b.addActionListener(this); jm.add(add_task_b = new JMenuItem("Task")); add_task_b.addActionListener(this); jm.add(add_text_b = new JMenuItem("Text")); @@ -200,6 +202,8 @@ public void actionPerformed(ActionEvent e) tree.addNode("NUMERIC"); if (source == add_signal_b) tree.addNode("SIGNAL"); + if (source == add_any_b) + tree.addNode("ANY"); if (source == add_task_b) tree.addNode("TASK"); if (source == add_text_b) diff --git a/java/jtraverser/src/main/resources/mds/jtraverser/any.gif b/java/jtraverser/src/main/resources/mds/jtraverser/any.gif index 6b7b6b60ff..4557110fa0 100644 Binary files a/java/jtraverser/src/main/resources/mds/jtraverser/any.gif and b/java/jtraverser/src/main/resources/mds/jtraverser/any.gif differ diff --git a/pydevices/RfxDevices/BCM_CONFIG.py b/pydevices/RfxDevices/BCM_CONFIG.py new file mode 100644 index 0000000000..7ce30610d1 --- /dev/null +++ b/pydevices/RfxDevices/BCM_CONFIG.py @@ -0,0 +1,209 @@ +from MDSplus import Device, Data, Int32, Float32 +from ctypes import CDLL,c_char_p,c_short,byref, c_int +from MDSplus.mdsExceptions import DevBAD_PARAMETER + +class BCM_CONFIG(Device): + """Beam Current Monitor Timing Configuration""" + parts = [ + {'path':':COMMENT','type':'text'}, + ] + for i in range(1,7): + parts.extend([ + {'path':'.CONF_%d'%(i),'type':'structure'}, + {'path':'.CONF_%d:DEV_PATH'%(i),'type':'text'}, + {'path':'.CONF_%d:MODE'%(i),'type':'text', 'value':'CONTINUOUS'}, + {'path':'.CONF_%d:START_TIME'%(i),'type':'numeric', 'value':0}, + {'path':'.CONF_%d:STOP_TIME'%(i),'type':'numeric', 'value':1}, + {'path':'.CONF_%d:PRE_SMP'%(i),'type':'numeric', 'value':0}, + {'path':'.CONF_%d:POST_SMP'%(i),'type':'numeric', 'value':10000}, + {'path':'.CONF_%d:CONT_FREQ'%(i),'type':'numeric', 'value':10000}, + {'path':'.CONF_%d:FAST_FREQ'%(i),'type':'numeric', 'value':10000}, + {'path':'.CONF_%d:SLOW_FREQ'%(i),'type':'numeric', 'value':10000}, + {'path':'.CONF_%d:SLOW_EV'%(i),'type':'text'}, + {'path':'.CONF_%d:FAST_EV'%(i),'type':'text'}, + {'path':'.CONF_%d:CONT_EV'%(i),'type':'text'}, + {'path':'.CONF_%d:SLOW_TRIG'%(i),'type':'numeric'}, + {'path':'.CONF_%d:FAST_TRIG'%(i),'type':'numeric'}, + {'path':'.CONF_%d:CONT_TRIG'%(i),'type':'numeric'}, + {'path':'.CONF_%d:FREQ'%(i),'type':'numeric'}, + {'path':'.CONF_%d:EV'%(i),'type':'text'}, + {'path':'.CONF_%d:TRIG'%(i),'type':'numeric'} + ]) + parts.extend([ + {'path':':START_ACTION','type':'action', + 'valueExpr':"Action(Dispatch('SERVER','INIT',50,None),Method(None,'init',head))", + 'options':('no_write_shot',)} + ]) + del(i) + + + modeDict = {'CONTINUOUS':'STREAMING', 'SLOW':'TRIGGER_STREAMING', 'FAST':'TRIGGER_STREAMING'} + + def init(self): + + error = False + for board in range(1,7): + + try: + devPath = self.__getattr__('conf_%d_dev_path'%(board)).getData() + except Exception as ex: + emsg = 'Missing device Path for board %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + mode = self.__getattr__('conf_%d_mode'%(board)).data() + except: + emsg = 'Missing device acquisition mode for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + self.getTree().getNode(devPath.getPath()+':MODE').putData(self.modeDict[mode]); + except Exception as ex: + emsg = 'Error on setting acquisition mode for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + + if mode == 'CONTINUOUS' : + + try: + freq = self.__getattr__('conf_%d_cont_freq'%(board)).data() + self.__getattr__('conf_%d_freq'%(board)).putData(Float32(freq)) + except Exception as ex: + emsg = 'Error on updating continuous frequency for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + mdsEvent = self.__getattr__('conf_%d_cont_ev'%(board)).getData() + self.__getattr__('conf_%d_ev'%(board)).putData(mdsEvent) + self.getTree().getNode(devPath.getPath()+':MDS_TRIG_EV').putData(mdsEvent); + except Exception as ex: + emsg = 'Error on updating continuous mds event for conf %d : %s'%(board,str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + trig = self.__getattr__('conf_%d_cont_trig'%(board)).data() + self.__getattr__('conf_%d_trig'%(board)).putData(Float32(trig)) + except Exception as ex: + emsg = 'Error on updating continuous trigger for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + + elif mode == 'SLOW' : + + try: + freq = self.__getattr__('conf_%d_slow_freq'%(board)).data() + self.__getattr__('conf_%d_freq'%(board)).putData(Float32(freq)) + except Exception as ex: + emsg = 'Error on updating continuous frequency for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + mdsEvent = self.__getattr__('conf_%d_slow_ev'%(board)).getData() + self.__getattr__('conf_%d_ev'%(board)).putData(mdsEvent) + self.getTree().getNode(devPath.getPath()+':MDS_TRIG_EV').putData(mdsEvent); + except Exception as ex: + emsg = 'Error on updating continuous mds event for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + trig = self.__getattr__('conf_%d_slow_trig'%(board)).data() + self.__getattr__('conf_%d_trig'%(board)).putData(Float32(trig)) + except Exception as ex: + emsg = 'Error on updating continuous trigger for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + elif mode == 'FAST' : + + try: + freq = self.__getattr__('conf_%d_fast_freq'%(board)).data() + self.__getattr__('conf_%d_freq'%(board)).putData(Float32(freq)) + except Exception as ex: + emsg = 'Error on updating continuous frequency for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + mdsEvent = self.__getattr__('conf_%d_fast_ev'%(board)).getData() + self.__getattr__('conf_%d_ev'%(board)).putData(mdsEvent) + self.getTree().getNode(devPath.getPath()+':MDS_TRIG_EV').putData(mdsEvent); + except Exception as ex: + emsg = 'Error on updating continuous mds event for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + trig = self.__getattr__('conf_%d_fast_trig'%(board)).data() + self.__getattr__('conf_%d_trig'%(board)).putData(Float32(trig)) + except Exception as ex: + emsg = 'Error on updating continuous trigger for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + else: + emsg = 'Invalid acquisition mode %s for conf %d'%(mode, board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + + if mode == 'SLOW' or mode == 'FAST' or mode == 'CONTINUOUS': + + try: + startTime = self.__getattr__('conf_%d_start_time'%(board)).data() + except Exception as ex: + emsg = 'Missing start time value for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + stopTime = self.__getattr__('conf_%d_stop_time'%(board)).data() + except Exception as ex: + emsg = 'Missing stop time value for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + preSmp = int( abs(startTime) * freq ); + self.__getattr__('conf_%d_pre_smp'%(board)).putData(Int32(preSmp)) + except Exception as ex: + emsg = 'Error on updating pre samples value for conf %d in %s acquisition mode : %s'%(board, mode, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + postSmp = int( abs(stopTime) * freq ); + self.__getattr__('conf_%d_post_smp'%(board)).putData(Int32(postSmp)) + except Exception as ex: + emsg = 'Error on updating post samples value for conf %d in %s acquisition mode : %s'%(board, mode, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + if error : + raise DevBAD_PARAMETER + + return 1 diff --git a/pydevices/RfxDevices/CRIO_FAU.py b/pydevices/RfxDevices/CRIO_FAU.py index a2da1ce64b..d393ae3d36 100644 --- a/pydevices/RfxDevices/CRIO_FAU.py +++ b/pydevices/RfxDevices/CRIO_FAU.py @@ -219,13 +219,13 @@ def init(self): bit=0 - pteEnaMask = long(0) - pteSlowFastMask = long(0) + pteEnaMask = int(0) + pteSlowFastMask = int(0) for mod in range(0,8): for ch in range(0,8): pteModeCode = self.TPEModeDict[getattr(self, 'module_%d_channel_%d_pte_mode'%(mod+1,ch)).data()] - pteEnaMask = pteEnaMask | ((pteModeCode & long(1) == 1) << bit) - pteSlowFastMask = pteSlowFastMask | ((pteModeCode & long(2) == 2) << bit) + pteEnaMask = pteEnaMask | ((pteModeCode & int(1) == 1) << bit) + pteSlowFastMask = pteSlowFastMask | ((pteModeCode & int(2) == 2) << bit) bit = bit + 1 print ('pteSlowFastMask ', pteSlowFastMask) @@ -268,7 +268,7 @@ def start_store(self): treePtr = c_void_p(0) - CRIO_FAU.niInterfaceLib.openTree(c_char_p(self.getTree().name), c_int(self.getTree().shot), byref(treePtr)) + CRIO_FAU.niInterfaceLib.openTree(c_char_p(self.getTree().name.encode('utf-8')), c_int(self.getTree().shot), byref(treePtr)) self.worker = self.AsynchStore() self.worker.daemon = True diff --git a/pydevices/RfxDevices/DEMOADC.py b/pydevices/RfxDevices/DEMOADC.py index 6be1b93ef4..1d30f4e64a 100644 --- a/pydevices/RfxDevices/DEMOADC.py +++ b/pydevices/RfxDevices/DEMOADC.py @@ -118,12 +118,14 @@ def init(self): # we use ctypes functions to convert python variable to appropriate C types to be passed to the external routine # try: print(address) - try: - deviceLibCDLL.initialize( - c_char_p(address), c_int(clockMode), c_int(pts)) - except: - print('Error initializing driver') - return 0 + deviceLibCDLL.initialize( + c_char_p(address.encode()), c_int(clockMode), c_int(pts)) + #try: + # deviceLibCDLL.initialize( + # c_char_p(address), c_int(clockMode), c_int(pts)) + #except: + # print('Error initializing driver') + # return 0 # return success return 1 @@ -158,7 +160,7 @@ def store(self): rawChan.append(DataArray()) rawChan.append(DataArray()) - status = deviceLib.acquire(c_char_p(addr), byref(rawChan[0]), byref( + status = deviceLib.acquire(c_char_p(addr.encode()), byref(rawChan[0]), byref( rawChan[1]), byref(rawChan[2]), byref(rawChan[3])) if status == -1: print ('Acquisition Failed') diff --git a/pydevices/RfxDevices/DEMOSTREAM.py b/pydevices/RfxDevices/DEMOSTREAM.py index 15f832ab65..4a35b8f606 100644 --- a/pydevices/RfxDevices/DEMOSTREAM.py +++ b/pydevices/RfxDevices/DEMOSTREAM.py @@ -57,12 +57,11 @@ def run(self): while not self.stopped: status = self.deviceLib.acquireChunk( - c_char_p(self.addr), byref(rawChan), c_int(self.NUM_CHUNK_SAMPLES)) + c_char_p(self.addr.encode()), byref(rawChan), c_int(self.NUM_CHUNK_SAMPLES)) if status == -1: print ('Acquisition Failed') return - Event.stream(0, 'demostream_chan', Float32(self.currTime), Float32(rawChan[0])) dataArr = Int16Array(rawChan) startTime = Float64(self.currTime) endTime = Float64( @@ -113,7 +112,7 @@ def start_store(self): self.worker.configure(deviceLib, addr, period, self.sig, self.NUM_CHUNK_SAMPLES, trigTime) self.saveWorker() - status = deviceLib.initializeStream(c_char_p(addr), c_float(frequency), c_float(trigTime)) + status = deviceLib.initializeStream(c_char_p(addr.encode()), c_float(frequency), c_float(trigTime)) self.worker.start() return 1 @@ -139,13 +138,15 @@ def init(self): print ('Missing Address in device') return 0 - clockDict = {1000: 1, 5000: 2, 10000: 3, 50000: 4, 100000: 5} try: - clockFreq = self.clock_freq.data() - clockMode = clockDict[clockFreq] + frequency = self.clock_freq.data() except: - print ('Missing or invalid clock frequency') + print ('Missing clock frequency') + return 0 + try: + trigTime = self.trig_source.data() + except: + print ('Missing trigger time') return 0 - deviceLib.initialize(c_char_p(addr), c_int(clockMode), c_int(0)) return 1 diff --git a/pydevices/RfxDevices/DTACQ_SUPERVISOR.py b/pydevices/RfxDevices/DTACQ_SUPERVISOR.py index f48a597bfa..6bfd629241 100644 --- a/pydevices/RfxDevices/DTACQ_SUPERVISOR.py +++ b/pydevices/RfxDevices/DTACQ_SUPERVISOR.py @@ -5,6 +5,8 @@ pass import socket import os +import sys +import numpy as np class DTACQ_SUPERVISOR(Device): """DTACQ device supervisor""" @@ -31,6 +33,29 @@ class DTACQ_SUPERVISOR(Device): {'path': ':DIO_BYTE2', 'type': 'text', 'value': 'INPUT'}, {'path': ':DIO_BYTE3', 'type': 'text', 'value': 'INPUT'}, {'path': ':DIO_BYTE4', 'type': 'text', 'value': 'INPUT'}, + {'path': '.PG1', 'type': 'structure'}, + {'path': '.PG1:SITE', 'type': 'numeric', 'value': 4}, + {'path': '.PG1:TRIG_SOURCE', 'type': 'text', 'value': 'SOFTWARE'}, + {'path': '.PG1:MODE', 'type': 'text', 'value': 'SINGLE'}, + {'path': '.PG1:TIME_DIV', 'type': 'numeric', 'value': 400000}, + {'path': '.PG1:LOOP_PERIOD', 'type': 'numeric', 'value': 0}, + {'path': '.PG1:D1_TIMES', 'type': 'numeric'}, + {'path': '.PG1:D2_TIMES', 'type': 'numeric'}, + {'path': '.PG1:D3_TIMES', 'type': 'numeric'}, + {'path': '.PG1:D4_TIMES', 'type': 'numeric'}, + {'path': '.PG1:D5_TIMES', 'type': 'numeric'}, + {'path': '.PG2', 'type': 'structure'}, + {'path': '.PG2:SITE', 'type': 'numeric', 'value': 5}, + {'path': '.PG2:TRIG_SOURCE', 'type': 'text', 'value': 'SOFTWARE'}, + {'path': '.PG2:MODE', 'type': 'text', 'value': 'SINGLE'}, + {'path': '.PG2:TIME_DIV', 'type': 'numeric', 'value': 400000}, + {'path': '.PG2:LOOP_PERIOD', 'type': 'numeric', 'value': 0}, + {'path': '.PG2:D1_TIMES', 'type': 'numeric'}, + {'path': '.PG2:D2_TIMES', 'type': 'numeric'}, + {'path': '.PG2:D3_TIMES', 'type': 'numeric'}, + {'path': '.PG2:D4_TIMES', 'type': 'numeric'}, + {'path': '.PG2:D5_TIMES', 'type': 'numeric'}, + {'path': ':PASSWD', 'type': 'text', 'value':'d-t1012q'}, {'path': ':INIT', 'type': 'action', 'valueExpr': "Action(Dispatch('MARTE_SERVER','INIT',50,None),Method(None,'init',head))", 'options': ('no_write_shot',)}] @@ -52,10 +77,111 @@ def __init__(self, netmask, tx_ip, rx_ip, gw, port, run0, play0, broadcast = 0, self.hudp_relay = hudp_relay self.spp = spp self.hudp_decim = hudp_decim +#INITIALIZE Pulse Generator + def mergeStl(self, inAlltimes, loopPeriod): + print('LOOP PERIOD: ', loopPeriod) + alltimes = inAlltimes.copy() + outPatterns=[] + outTimes = [] + currPattern = int(0) + while True: + minTime = sys.maxsize + minIdx = -1 + for idx in range(len(alltimes)): + if len(alltimes[idx]) == 0: + continue + if alltimes[idx][0] < minTime: + minTime = alltimes[idx][0] + minIdx = idx + if minIdx < 0: + if loopPeriod > 0: + outTimes.append(int(loopPeriod)) + outPatterns.append(outPatterns[-1]) + return outPatterns, outTimes + mask = currPattern & (1 << minIdx) + if(mask != 0): #corresponding bit flips to 0 + currPattern = currPattern & ~(1 << minIdx) + else: #flips to 1 + currPattern = currPattern | (1 << minIdx) + alltimes[minIdx] = alltimes[minIdx][1:] + #check if other times are equals + for idx in range(len(alltimes)): + if len(alltimes[idx]) == 0: + continue + if alltimes[idx][0] == minTime: + mask = currPattern & (1 << idx) + if(mask != 0): #corresponding bit flips to 0 + currPattern = currPattern & ~(1 << idx) + else: #flips to 1 + currPattern = currPattern | (1 << idx) + alltimes[idx] = alltimes[idx][1:] + outPatterns.append(currPattern) + outTimes.append(minTime) + + + + def pgInitSpec(self, pgIdx): + site = getattr(self, 'pg%d_site' % (pgIdx)).data() + try: + trigSourceT = getattr(self, 'pg%d_trig_source' % (pgIdx)).data() + trigSourceDict = {'TRIG_IN':'1,0,1', 'SOFTWARE': '1,1,1','ADC_TRIG': '1,2,1','SITE4_TRIG': '1,5,1','SITE5_TRIG': '1,6,1'} + trigSource = trigSourceDict[trigSourceT] + except: + print('Invalid trigger source for PG '+str(pgIdx)) + raise mdsExceptions.TclFAILED_ESSENTIAL + try: + modeT = getattr(self, 'pg%d_mode' % (pgIdx)).data() + modeDict = {'SINGLE': 0, 'LOOP': 2, 'LOOPWAIT': 3} + mode = modeDict[modeT] + except: + print('Invalid mode for PG '+str(pgIdx)) + raise mdsExceptions.TclFAILED_ESSENTIAL + if mode == 2: + try: + loopPeriod = getattr(self, 'pg%d_loop_period' % (pgIdx)).data() + except: + print('No period specified for LOOP mode') + raise mdsExceptions.TclFAILED_ESSENTIAL + else: + loopPeriod = -1 + try: + timeDiv = int(getattr(self, 'pg%d_time_div' % (pgIdx)).data()) + except: + print('Cannot get Time division for PG '+str(pgIdx)) + raise mdsExceptions.TclFAILED_ESSENTIAL + alltimes = [] + for chIdx in range(1,5): + try: + times = getattr(self, 'pg%d_d%d_times' % (pgIdx, chIdx)).data() + except: + print('No time array defined for D'+str(chIdx)+' IN PG'+str(pgIdx)) + continue + if loopPeriod != -1 and times[-1] > loopPeriod: + print('Invalid times definition: times must be less that loop period') + raise mdsExceptions.TclFAILED_ESSENTIAL + alltimes.append(times) + if len(alltimes) == 0: + print('No Time signal defined') + return + outPatterns, outTimes = self.mergeStl(alltimes, loopPeriod) + tempF = open('temp.stl', 'w') + for i in range(len(outTimes)): + tempF.write(str(outTimes[i])+','+str(outPatterns[i])+'\n') + tempF.close() + command = 'sshpass -p'+self.passwd.data()+' scp temp.stl root@'+self.ip_addr.data()+':' + print(command) + os.system(command) + command = 'sshpass -p'+self.passwd.data()+' ssh root@'+self.ip_addr.data()+' -t \'sh -l -c "CSCALE='+str(timeDiv)+' SITE='+str(site)+' /usr/local/CARE/pg_test ' +str(mode)+' temp.stl"\'' + print(command) + os.system(command) + + def pgInit(self): + self.pgInitSpec(1) + self.pgInitSpec(2) # INIT def init(self): - import hudp_setup +# import hudp_setup print('INIT') try: ipAddr = self.ip_addr.data() @@ -237,7 +363,9 @@ def init(self): try: dtackAi = self.ai_b_device.getData() hasBulkAi = True - dtackAi.parameters_par_1_value.putData(Float64(clockFreq)) + dtackAi.parameters_par13_value.putData(Int32(clockFreq)) #num samples +# dtackAi.parameters_par_1_value.putData(Float64(clockFreq/numSamples)) + dtackAi.parameters_par_1_value.putData(Float64(1)) #1 segment per second dtackAi.parameters_par_2_value.putData(Float64(triggerTime)) dtackAi.parameters_par_3_value.putData(Int32(1)) dtackAi.parameters_par_4_value.putData(len(aiSites)) @@ -260,6 +388,8 @@ def init(self): print('Frequency division not defined for realtime device') raise mdsExceptions.TclFAILED_ESSENTIAL + + dtackAi.parameters_par13_value.putData(Int32(1)) #num samples dtackAi.parameters_par_1_value.putData(Float64(clockFreq/freqDiv)) dtackAi.parameters_par_2_value.putData(Float64(triggerTime)) dtackAi.parameters_par_3_value.putData(Int32(2)) diff --git a/pydevices/RfxDevices/MARTE2_COMPONENT.py b/pydevices/RfxDevices/MARTE2_COMPONENT.py index 37fa251448..6a9b301bb6 100644 --- a/pydevices/RfxDevices/MARTE2_COMPONENT.py +++ b/pydevices/RfxDevices/MARTE2_COMPONENT.py @@ -2781,9 +2781,9 @@ def getMarteInputInfo(self, threadMap, gams, dataSources, gamList, isSynch): isInputStructField = False gamText += ' '+signalDict['name']+' = {\n' if isInputStructField: - gamText += ' DataSource = '+gamName+'_Expanded_Output_DDB\n' + gamText += ' DataSource = '+dataSourceName+'_Expanded_Output_DDB\n' else: - gamText += ' DataSource = '+gamName+'_Output_DDB\n' + gamText += ' DataSource = '+dataSourceName+'_Output_DDB\n' gamText += ' Type = '+signalDict['type']+'\n' if 'dimensions' in signalDict: dimensions = signalDict['dimensions'] diff --git a/pydevices/RfxDevices/MARTE_RF_CTRL.py b/pydevices/RfxDevices/MARTE_RF_CTRL.py new file mode 100644 index 0000000000..664195863a --- /dev/null +++ b/pydevices/RfxDevices/MARTE_RF_CTRL.py @@ -0,0 +1,56 @@ +# +# Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# Redistributions in binary form must reproduce the above copyright notice, this +# list of conditions and the following disclaimer in the documentation and/or +# other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +try: + MARTE_COMMON = __import__('MARTE_COMMON', globals(), level=1).MARTE_COMMON +except: + MARTE_COMMON = __import__('MARTE_COMMON', globals()).MARTE_COMMON + +class MARTE_RF_CTRL(MARTE_COMMON): + parNames = ['RF1_KP', 'RF1_KI', 'RF1_KD', 'RF2_KP', 'RF2_KI', 'RF2_KD', 'RF3_KP', 'RF3_KI', 'RF3_KD', 'RF4_KP', 'RF4_KI', 'RF4_KD', 'triggerTime', 'frequency'] + parValues = ['1','0','0','1','0','0','1','0','0','1','0','0', '0.', '1000.'] + waveParNames = [] + + parts = list(MARTE_COMMON.parts) + parts.append({'path':'.PARAMS', 'type':'structure'}) + parts.append({'path':'.PARAMS:NUM_ACTIVE', 'type':'numeric', 'value':len(parNames)}) + for i in range(len(parNames)): + parts.append({'path':'.PARAMS:PAR_%03d'%(i+1), 'type':'structure'}) + parts.append({'path':'.PARAMS:PAR_%03d:DESCRIPTION'%(i+1), 'type':'text'}) + parts.append({'path':'.PARAMS:PAR_%03d:NAME'%(i+1), 'type':'text', 'value':parNames[i]}) + parts.append({'path':'.PARAMS:PAR_%03d:TYPE'%(i+1), 'type':'text'}) + parts.append({'path':'.PARAMS:PAR_%03d:DIMS'%(i+1), 'type':'numeric'}) + parts.append({'path':'.PARAMS:PAR_%03d:DATA'%(i+1), 'type':'numeric','valueExpr':parValues[i]}) + + parts.append({'path':'.WAVE_PARAMS', 'type':'structure'}) + parts.append({'path':'.WAVE_PARAMS:NUM_ACTIVE', 'type':'numeric', 'value':0}) + for i in range(len(waveParNames)): + parts.append({'path':'.WAVE_PARAMS:WAVE_%03d'%(i+1), 'type':'structure'}) + parts.append({'path':'.WAVE_PARAMS:WAVE_%03d:DESCRIPTION'%(i+1), 'type':'text'}) + parts.append({'path':'.WAVE_PARAMS:WAVE_%03d:NAME'%(i+1), 'type':'text', 'value':waveParNames[i]}) + parts.append({'path':'.WAVE_PARAMS:WAVE_%03d:X'%(i+1), 'type':'numeric'}) + parts.append({'path':'.WAVE_PARAMS:WAVE_%03d:Y'%(i+1), 'type':'numeric'}) + del(parNames,parValues,waveParNames,i) + diff --git a/pydevices/RfxDevices/MITICA_SETUP.py b/pydevices/RfxDevices/MITICA_SETUP.py index 5acd131382..8e6ec614da 100644 --- a/pydevices/RfxDevices/MITICA_SETUP.py +++ b/pydevices/RfxDevices/MITICA_SETUP.py @@ -128,8 +128,8 @@ class MITICA_SETUP(Device): parts.append({'path':'.MAGPS.WAVE_REC:MIN_Y', 'type':'numeric'}) parts.append({'path':'.MAGPS.WAVE_REC:MAX_Y', 'type':'numeric'}) - parts.append({'path':'.MGVS:VC3001_TURNS', 'type':'numeric', 'value':0}) - parts.append({'path':'.MGVS:VC3002_TURNS', 'type':'numeric', 'value':0}) + parts.append({'path':'.MGVS:VC5001_TURNS', 'type':'numeric', 'value':0}) + parts.append({'path':'.MGVS:VC5002_TURNS', 'type':'numeric', 'value':0}) parts.append({'path':'.MITICA:TIME_OF_INTE', 'type':'numeric'}) @@ -149,11 +149,9 @@ class MITICA_SETUP(Device): parts.append({'path':'.MGVS.WAVE_%d:LABEL'%(i+1), 'type':'text', 'value':'MGVS wave %d'%(i+1)}) parts.append({'path':'.MAGPS.WAVE_%d:LABEL'%(i+1), 'type':'text', 'value':'MAGPS wave %d'%(i+1)}) - - - parts.append({'path':'.MGVS:PRESET_PRES', 'type':'numeric', 'value':0.2}) - parts.append({'path':'.MGVS:TANK' , 'type':'text' , 'value':'3000'}) - parts.append({'path':'.MGVS:GAS_TYPE' , 'type':'text' , 'value':'3090'}) + parts.append({'path':'.MGVS:GISB_PSP', 'type':'numeric', 'value':0.2}) + parts.append({'path':'.MGVS:GISB_TANK' , 'type':'text' , 'value':'3000'}) + parts.append({'path':'.MGVS:GISB_GAS_TYP' , 'type':'text' , 'value':'H2'}) parts.append({'path':'.MISEPS:ISRF_TE_V' , 'type':'numeric', 'value':10000}) parts.append({'path':'.MISEPS:RF_REG_MODE', 'type':'text' , 'value':'None'}) @@ -161,6 +159,21 @@ class MITICA_SETUP(Device): parts.append({'path':'.MISEPS:CS1_I_REF' , 'type':'numeric', 'value':0}) parts.append({'path':'.MISEPS:CS2_I_REF' , 'type':'numeric', 'value':0}) + parts.append({'path':'.MGVS:VC5003_TURNS', 'type':'numeric', 'value':0}) + parts.append({'path':'.MGVS:GISC_TANK' , 'type':'text' , 'value':'3000'}) + parts.append({'path':'.MGVS:GISC_GAS_TYP' , 'type':'text' , 'value':'H2'}) + parts.append({'path':'.MGVS:GISC_PSP', 'type':'numeric', 'value':0.2}) + + + for i in range(8,16): + parts.append({'path':'.MGVS.WAVE_%d'%(i+1), 'type':'structure'}) + parts.append({'path':'.MGVS.WAVE_%d:WAVE'%(i+1), 'type':'signal'}) + parts.append({'path':'.MGVS.WAVE_%d:MIN_X'%(i+1), 'type':'numeric'}) + parts.append({'path':'.MGVS.WAVE_%d:MAX_X'%(i+1), 'type':'numeric'}) + parts.append({'path':'.MGVS.WAVE_%d:MIN_Y'%(i+1), 'type':'numeric'}) + parts.append({'path':'.MGVS.WAVE_%d:MAX_Y'%(i+1), 'type':'numeric'}) + parts.append({'path':'.MGVS.WAVE_%d:LABEL'%(i+1), 'type':'text', 'value':'MGVS wave %d'%(i+1)}) + del(i) diff --git a/pydevices/RfxDevices/NI6683REC.py b/pydevices/RfxDevices/NI6683REC.py index ad8e2cfe30..3b861deb8a 100644 --- a/pydevices/RfxDevices/NI6683REC.py +++ b/pydevices/RfxDevices/NI6683REC.py @@ -1,74 +1,68 @@ -from MDSplus import mdsExceptions, Device, Data, Int64 +from MDSplus import mdsExceptions, Device, Data, Range, Dimension, Window, Int32, Float32, Float64, Int64, Int8, Tree from threading import Thread -from ctypes import CDLL, byref, c_longlong, c_int, Structure, c_ubyte +from ctypes import CDLL, byref, c_longlong, c_int, c_void_p, c_float, c_char_p, c_uint, c_short, c_byte, c_double, get_errno, Structure, c_ubyte import os import time +import sys, traceback import select +import errno from datetime import datetime class NI6683REC(Device): """ niSync PXIe SPIDER timing device """ - parts = [ - {'path': ':COMMENT', 'type': 'text'}, - {'path': ':DEV_TYPE', 'type': 'text', 'value': 'PXI6683H'}, - {'path': ':DEV_NUM', 'type': 'numeric', 'value': 0}, - {'path': ':TRIG_DEC_CNT', 'type': 'numeric', 'value': 1}, - {'path': ':TAIUTC_DELAY', 'type': 'numeric', - 'valueExpr': 'Data.compile("37000000000Q")'}, - {'path': '.PULSE_TIME', 'type': 'structure'}, - {'path': '.PULSE_TIME:REF_TIME', 'type': 'numeric', 'value': -6.}, - {'path': '.PULSE_TIME:TRIG_TERM', 'type': 'text', 'value': 'PFI1'}, - {'path': '.PULSE_TIME:TRIG_EDGE', 'type': 'text', 'value': 'RISING'}, - {'path': '.PULSE_TIME:TAI_NS', 'type': 'numeric', - 'options': ('no_write_model')}, - {'path': '.PULSE_TIME:UTC_NS', 'type': 'numeric', - 'valueExpr': 'Data.compile("$1 - $2",head.pulse_time_tai_ns, head.taiutc_delay)'}, - {'path': '.PULSE_TIME:DATE', 'type': 'text', - 'options': ('no_write_model,')}, - ] + parts=[{'path':':COMMENT', 'type':'text'}, + {'path':':DEV_TYPE', 'type':'text', 'value':'PXI6683H'}, + {'path':':DEV_NUM', 'type':'numeric', 'value':0}, + {'path':':TRIG_DEC_CNT', 'type':'numeric', 'value':1}, + {'path':':TAIUTC_DELAY', 'type':'numeric', 'valueExpr': 'Data.compile("37000000000Q")' }, + {'path':'.PULSE_TIME', 'type':'structure'}, + {'path':'.PULSE_TIME:REF_TIME', 'type':'numeric', 'value':-6.}, + {'path':'.PULSE_TIME:TRIG_TERM', 'type':'text', 'value':'PFI1'}, + {'path':'.PULSE_TIME:TRIG_EDGE', 'type':'text', 'value':'RISING'}, + {'path':'.PULSE_TIME:TAI_NS', 'type':'numeric','options':('no_write_model')}, + {'path':'.PULSE_TIME:UTC_NS', 'type':'numeric', + 'valueExpr': 'Data.compile("$1 - $2",head.pulse_time_tai_ns, head.taiutc_delay)'}, + {'path':'.PULSE_TIME:DATE' , 'type':'text','options':('no_write_model')}] + for i in range(8): - parts.extend([ - {'path': '.TRIG_%d' % (i+1), 'type': 'structure'}, - {'path': '.TRIG_%d:COMMENT' % (i+1), 'type': 'text'}, - {'path': '.TRIG_%d:TERM' % ( - i+1), 'type': 'text', 'value': 'PFI2'}, - {'path': '.TRIG_%d:EDGE' % ( - i+1), 'type': 'text', 'value': 'RISING'}, - {'path': '.TRIG_%d:TAI_NS' % ( - i+1), 'type': 'numeric', 'options': ('no_write_model')}, - {'path': '.TRIG_%d:UTC_NS' % (i+1), 'type': 'numeric', - 'valueExpr': 'Data.compile("($1 - $2)", head.trig_%d_tai_ns, head.taiutc_delay)' % (i+1)}, - {'path': '.TRIG_%d:TIME' % (i+1), 'type': 'numeric', - 'valueExpr': 'Data.compile("data(($1 - $2)/1000000000.)+$3", head.trig_%d_tai_ns, head.pulse_time_tai_ns, head.pulse_time_ref_time)' % (i+1)}, - ]) - - parts.extend([ - {'path': ':INIT_ACTION', 'type': 'action', - 'valueExpr': "Action(Dispatch('TIMING_SERVER','INIT',50,None),Method(None,'init',head))", - 'options': ('no_write_shot',)}, - {'path': ':START_ACTION', 'type': 'action', - 'valueExpr': "Action(Dispatch('TIMING_SERVER','READY',50,None),Method(None,'start',head))", - 'options': ('no_write_shot',)}, - {'path': ':STOP_ACTION', 'type': 'action', - 'valueExpr': "Action(Dispatch('TIMING_SERVER','POST_PULSE_CHECK',50,None),Method(None,'stop',head))", - 'options': ('no_write_shot',)}, - ]) - - NISYNC_DEVICE_TYPE_UNKNOWN = c_int(-1) - NISYNC_DEVICE_TYPE_PXI6682 = c_int(0) - NISYNC_DEVICE_TYPE_PCI1588 = c_int(1) - NISYNC_DEVICE_TYPE_PXI6683 = c_int(2) + parts.append({'path':'.TRIG_%d'%(i+1), 'type':'structure'}) + parts.append({'path':'.TRIG_%d:COMMENT'%(i+1), 'type':'text'}) + parts.append({'path':'.TRIG_%d:TERM'%(i+1), 'type':'text', 'value':'PFI2'}) + parts.append({'path':'.TRIG_%d:EDGE'%(i+1), 'type':'text', 'value':'RISING'}) + parts.append({'path':'.TRIG_%d:TAI_NS'%(i+1), 'type':'numeric','options':('no_write_model')}) + parts.append({'path':'.TRIG_%d:UTC_NS'%(i+1), 'type':'numeric', + 'valueExpr': 'Data.compile("($1 - $2)", head.trig_%d_tai_ns, head.taiutc_delay)'%(i+1)}) + parts.append({'path':'.TRIG_%d:TIME'%(i+1), 'type':'numeric', + 'valueExpr': 'Data.compile("data(($1 - $2)/1000000000.)+$3", head.trig_%d_tai_ns, head.pulse_time_tai_ns, head.pulse_time_ref_time)'%(i+1)}) + + + parts.append({'path':':INIT_ACTION','type':'action', + 'valueExpr':"Action(Dispatch('TIMING_SERVER','INIT',50,None),Method(None,'init',head))", + 'options':('no_write_shot',)}) + parts.append({'path':':START_ACTION','type':'action', + 'valueExpr':"Action(Dispatch('TIMING_SERVER','READY',50,None),Method(None,'start',head))", + 'options':('no_write_shot',)}) + parts.append({'path':':STOP_ACTION','type':'action', + 'valueExpr':"Action(Dispatch('TIMING_SERVER','POST_PULSE_CHECK',50,None),Method(None,'stop',head))", + 'options':('no_write_shot',)}) + + + + + NISYNC_DEVICE_TYPE_UNKNOWN = c_int(-1) + NISYNC_DEVICE_TYPE_PXI6682 = c_int(0) + NISYNC_DEVICE_TYPE_PCI1588 = c_int(1) + NISYNC_DEVICE_TYPE_PXI6683 = c_int(2) NISYNC_DEVICE_TYPE_PXI6683H = c_int(3) - NISYNC_READ_BLOCKING = c_int(0) # Wait until some data is available - # Return immediately even if no data is available - NISYNC_READ_NONBLOCKING = c_int(1) + NISYNC_READ_BLOCKING = c_int(0) # Wait until some data is available + NISYNC_READ_NONBLOCKING = c_int(1) # Return immediately even if no data is available - NISYNC_EDGE_RISING = c_int(0) - NISYNC_EDGE_FALLING = c_int(1) - NISYNC_EDGE_ANY = c_int(2) - NISYNC_EDGE_INVALID = c_int(3) + NISYNC_EDGE_RISING = c_int(0) + NISYNC_EDGE_FALLING = c_int(1) + NISYNC_EDGE_ANY = c_int(2) + NISYNC_EDGE_INVALID = c_int(3) NISYNC_PFI0 = c_int(0) NISYNC_PFI1 = c_int(1) @@ -121,16 +115,23 @@ class NI6683REC(Device): NISYNC_ENET_TRANSMIT_LATENCY = c_int(3) NISYNC_ENET_RECEIVE_LATENCY = c_int(4) - DevTypeDict = {'UNKNOWN': -1, 'PXI6682': 0, - 'PCI1588': 1, 'PXI6683': 2, 'PXI6683H': 3} - trigTermDict = {'PFI0': 0, 'PFI1': 1, 'PFI2': 2, 'TRIG0': 11, 'TRIG1': 12, - 'TRIG2': 13, 'TRIG3': 14, 'TRIG4': 15, 'TRIG5': 16, 'TRIG6': 17, 'TRIG7': 18} - trigEdgeDict = {'RISING': 0, 'FALLING': 1, 'ANY': 2, 'INVALID': 3} + NISYNC_PTPD_DISABLED = c_int(0) + NISYNC_PTPD_INITIALIZING = c_int(1) + NISYNC_PTPD_SLAVE = c_int(2) + NISYNC_PTPD_LISTENING = c_int(3) + NISYNC_PTPD_MASTER = c_int(4) + NISYNC_PTPD_FAULTY = c_int(5) + + + DevTypeDict = {'UNKNOWN':-1 , 'PXI6682':0, 'PCI1588':1, 'PXI6683':2, 'PXI6683H':3} + trigTermDict = {'PFI0':0, 'PFI1':1, 'PFI2':2, 'TRIG0':11, 'TRIG1':12, 'TRIG2':13, 'TRIG3':14, 'TRIG4':15, 'TRIG5':16, 'TRIG6':17, 'TRIG7':18} + trigEdgeDict = {'RISING':0, 'FALLING':1, 'ANY':2, 'INVALID':3} class nisyncTimestampNanos(Structure): - # creates a struct to match nisync_timestamp_nanos + #creates a struct to match nisync_timestamp_nanos _fields_ = [('edge', c_ubyte), - ('nanos', c_longlong)] + ('nanos', c_longlong)] + #devFd = None NiSyncLib = None @@ -139,38 +140,39 @@ class nisyncTimestampNanos(Structure): workers = {} -# National Instruments Sync Device Manager +######### National Instruments Sync Device Manager def saveInfo(self): NI6683REC.fds[self.nid] = self.devFd NI6683REC.nids[self.nid] = self.timeNid def restoreInfo(self): - try: + try: print ('restoreInfo') self.devFd = NI6683REC.fds[self.nid] self.timeNid = NI6683REC.nids[self.nid] - except: + except: raise mdsExceptions.TclFAILED_ESSENTIAL - + def closeInfo(self): try: self.devFd = NI6683REC.fds[self.nid] for fd in self.devFd: - if fd == -1: - continue + if fd == -1 : + continue os.close(fd) del(NI6683REC.fds[self.nid]) - self.devFd = -1 + self.devFd = -1 del NI6683REC.nids[self.nid] except: pass + return def initializeInfo(self): if NI6683REC.NiSyncLib is None: - NI6683REC.NiSyncLib = CDLL("libnisync.so") - + NI6683REC.NiSyncLib = CDLL("libnisync.so") + try: devType = c_int(self.DevTypeDict[self.dev_type.data()]) except: @@ -187,268 +189,346 @@ def initializeInfo(self): except: trigTerm = c_int(-1) + + fd = NI6683REC.NiSyncLib.nisync_open_device(devType, devNum) + if not fd < 0 : + ptpd_state = c_int(0) + #status = NI6683REC.NiSyncLib.nisync_set_ptpd_state(fd, self.NISYNC_PTPD_SLAVE) + status = NI6683REC.NiSyncLib.nisync_get_ptpd_state(fd, byref(ptpd_state)) + if status < 0 : + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Read PTPd service state') + raise mdsExceptions.TclFAILED_ESSENTIAL + print("PTPd service state %d"%(ptpd_state.value)) + if ptpd_state.value != 2 : + Data.execute('DevLogErr($1,$2)', self.getNid(), 'PTPd service is not running or not synchronized') + raise mdsExceptions.TclFAILED_ESSENTIAL + else: + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot open device %s num %d Timing Device'%(devType, devNum)) + raise mdsExceptions.TclFAILED_ESSENTIAL + os.close(fd) + + self.devFd = [] self.timeNid = {} try: - #print "test",devType, devNum, trigTerm, self.NISYNC_READ_NONBLOCKING - self.devFd.append(NI6683REC.NiSyncLib.nisync_open_terminal( - devType, devNum, trigTerm, self.NISYNC_READ_NONBLOCKING)) + + print ("test",devType, devNum, trigTerm, self.NISYNC_READ_NONBLOCKING) + self.devFd.append(NI6683REC.NiSyncLib.nisync_open_terminal(devType, devNum, trigTerm, self.NISYNC_READ_NONBLOCKING)); print ("Pulse ", trigTermName, self.devFd[0]) nids = [] - nids.append(self.pulse_time_tai_ns) - nids.append(self.pulse_time_date) - - self.timeNid[self.devFd[0]] = nids - - if self.devFd < 0: - Data.execute('DevLogErr($1,$2)', self.getNid( - ), 'Cannot open terminal %s NiSync Timing Device' % (trigTermName)) + nids.append(self.pulse_time_tai_ns.getPath()) + nids.append(self.pulse_time_date.getPath()) + + self.timeNid[self.devFd[0]] = nids + + if self.devFd[0] < 0 : + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot open terminal %s NiSync Timing Device'%(trigTermName)) raise mdsExceptions.TclFAILED_ESSENTIAL - + for tr in range(8): - if getattr(self, 'trig_%d' % (tr+1)).isOn(): + if getattr(self, 'trig_%d'%(tr+1)).isOn(): try: - trigTermName = getattr( - self, 'trig_%d_term' % (tr+1)).data() + trigTermName = getattr(self, 'trig_%d_term'%(tr+1)).data() trigTerm = c_int(self.trigTermDict[trigTermName]) except: - Data.execute('DevLogErr($1,$2)', self.getNid( - ), 'Invalid terminal for trigger %s ' % (tr+1)) + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid terminal for trigger %s '%(tr+1)) continue - #print "TRIG_%d"%(tr+1),devType, devNum, trigTerm, self.NISYNC_READ_NONBLOCKING - print ("TRIG_%d" % (tr+1), trigTermName, trigTerm) - self.devFd.append(NI6683REC.NiSyncLib.nisync_open_terminal( - devType, devNum, trigTerm, self.NISYNC_READ_NONBLOCKING)) - + #print ("TRIG_%d"%(tr+1),devType, devNum, trigTerm, self.NISYNC_READ_NONBLOCKING) + print ("TRIG_%d"%(tr+1), trigTermName, trigTerm) + self.devFd.append(NI6683REC.NiSyncLib.nisync_open_terminal(devType, devNum, trigTerm, self.NISYNC_READ_NONBLOCKING)) + nids = [] - nids.append(getattr(self, 'trig_%d_tai_ns' % (tr+1))) - self.timeNid[self.devFd[len(self.devFd)-1]] = nids + nids.append( getattr(self, 'trig_%d_tai_ns'%(tr+1)).getPath() ) + self.timeNid[self.devFd[len(self.devFd)-1]] = nids - print ("devFd", trigTermName, - self.devFd[len(self.devFd)-1]) + print ("devFd", trigTermName, self.devFd[len(self.devFd)-1]) else: self.devFd.append(-1) + for pp, nn in self.timeNid.items(): + for n in nn: + print( self.getNode(n).getPath() ) + except BaseException as e: print (str(e)) - Data.execute('DevLogErr($1,$2)', self.getNid( - ), 'Exception on NiSync Timing Device on open terminal %s ' % (trigTermName)) + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Exception on NiSync Timing Device on open terminal %s '%(trigTermName)) raise mdsExceptions.TclFAILED_ESSENTIAL + return + -# Worker Management +################################### Worker Management def saveWorker(self): - NI6683REC.workers[self.getNid()] = self.worker + NI6683REC.workers[self.getNid()] = self.worker def restoreWorker(self): - try: - self.worker = NI6683REC.workers[self.nid] - except: - self.worker = None - print('Cannot restore worker!!') + try: + self.worker = NI6683REC.workers[self.nid] + except: + self.worker = None + print('Cannot restore worker!!') -# AsynchStore class +########################AsynchStore class class AsynchStore(Thread): def configure(self, device): self.device = device self.stopReq = False - + def run(self): + self.device.setTree( + Tree(self.device.getTree().name, self.device.getTree().shot)) + #self.device = self.device.copy() + + poll = select.poll() - for fd in self.device.devFd: - if fd == -1: - continue - print ("Poll register fd", fd) - poll.register(fd, select.POLLIN) + for fd in self.device.devFd : + if fd == -1 : + continue + print ("Poll register fd", fd) + poll.register(fd, select.POLLIN) nTimestamps = c_int(1000) #ts = self.device.nisyncTimestampNanos() - ts = (self.device.nisyncTimestampNanos*1000)() + ts=(self.device.nisyncTimestampNanos*1000)() try: - tai_utc_delay = self.device.taiutc_delay.data() + tai_utc_delay = self.device.taiutc_delay.data() except: - tai_utc_delay = 37000000000 - self.device.taiutc_delay.putData(Int64(tai_utc_delay)) - + tai_utc_delay = 37000000000; + self.device.taiutc_delay.putData(Int64(tai_utc_delay)) + + """ + for pp, nn in self.device.timeNid.items(): + for n in nn: + print("Node ", n ) + print("Node Path ", self.device.getNode(n).getPath() ) + """ + + first = 1 timeout = 1000 ts_nanos_prev = 0 while not self.stopReq: - poolfd = poll.poll(timeout) - for fd1, event in poolfd: - print ("fd = ", fd1) - print ("event = ", event) - count = NI6683REC.NiSyncLib.nisync_read_timestamps_ns( - fd1, byref(ts), nTimestamps) - print ("count = ", count) - print ("------------------------------------------------") - for i in range(count): - print (1000000000. / - (ts[i].nanos-ts_nanos_prev), ts[i].nanos, count) - dt = datetime.fromtimestamp(ts[i].nanos // 1000000000) - dt_str = dt.strftime('%Y-%m-%d %H:%M:%S') + "." + str( - int(((ts[i].nanos-tai_utc_delay) % 1000000000))).zfill(9) - print (dt_str) - - nids = self.device.timeNid[fd1] - try: - if (len(nids) == 2): - print (nids[0].getPath()) - nids[0].putData(Int64(ts[i].nanos)) - print (nids[0].getPath()) - nids[1].putData(dt_str) - else: - print (nids[0].getPath()) - nids[0].putRow(1000, Int64( - ts[i].nanos), Int64(ts[i].nanos)) - except BaseException as e: - print (e) - print('Error save timestamp') - - ts_nanos_prev = ts[i].nanos - # break - print ("------------------------------------------------") - time.sleep(1) - - for fd in self.device.devFd: - if fd == -1: - continue - poll.unregister(fd) - + poolfd = poll.poll(timeout) + for fd1, event in poolfd : + print( "fd = ", fd1) + print( "event = ", event) + count = NI6683REC.NiSyncLib.nisync_read_timestamps_ns(fd1, byref(ts), nTimestamps); + print( "count = ", count) + print( "tai_utc_delay = ", tai_utc_delay) + print( "------------------------------------------------") + for i in range(count) : + print( 1000000000. / (ts[i].nanos-ts_nanos_prev), ts[i].nanos, count ) + dt = datetime.fromtimestamp((ts[i].nanos-tai_utc_delay) // 1000000000) + dt_str = dt.strftime('%Y-%m-%d %H:%M:%S') +"."+ str(int(( (ts[i].nanos-tai_utc_delay) % 1000000000))).zfill(9) + print( dt_str) + + nids = self.device.timeNid[fd1]; + try: + if ( len(nids) == 2 ) : + print( self.device.getNode(nids[0]).getPath()) + #nids[0].putData(Int64(ts[i].nanos)) + self.device.getNode(nids[0]).putRow(1000, Int64(ts[i].nanos), Int64(ts[i].nanos) ) + if first : + first = 0 + print( self.device.getNode(nids[1]).getPath()) + self.device.getNode(nids[1]).putData(dt_str) + else: + print( self.device.getNode(nids[0]).getPath()) + self.device.getNode(nids[0]).putRow(1000, Int64(ts[i].nanos), Int64(ts[i].nanos) ) + except BaseException as e: + print( e) + print('Error save timestamp') + + """ + try: + self.device.pulse_time_tai_ns.putData( Int64(ts.nanos)) + self.device.pulse_time_tai_s.putData(Int64(ts.nanos//1000000000)) + self.device.pulse_time_date.putData(dt_str) + except BaseException as e: + print (e) + print('Error save timestamp') + """ + ts_nanos_prev = ts[i].nanos + #break + print ("------------------------------------------------") + time.sleep(1) + + for fd in self.device.devFd : + if fd == -1 : + continue + poll.unregister(fd) + print ('AsynchStore stop') + return + def stop(self): self.stopReq = True - -# End Inner class AsynchStore + +#############End Inner class AsynchStore def init(self): try: - self.restoreInfo() + self.restoreInfo() self.stop() except: print ('Not started') + pass + - -# Configuration check +#Configuration check try: devType = self.DevTypeDict[self.dev_type.data()] except: - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Device Type module Undefined') + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Device Type module Undefined') raise mdsExceptions.TclFAILED_ESSENTIAL try: - devNum = self.dev_num.data() + devNum = self.dev_num.data(); except: - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Device number Undefined') + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Device number Undefined') raise mdsExceptions.TclFAILED_ESSENTIAL + """ + try: + devTerm = self.trigTermDict[self.trig_term.data()] + except: + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Device terminal Undefined') + raise mdsExceptions.TclFAILED_ESSENTIAL + """ + try: trigDecCnt = c_int(self.trig_dec_cnt.data()) except: - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Trigger decimation count Undefined') + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Trigger decimation count Undefined') raise mdsExceptions.TclFAILED_ESSENTIAL try: - trigEdge = c_int( - self.trigEdgeDict[self.pulse_time_trig_edge.data()]) + trigEdge = c_int(self.trigEdgeDict[self.pulse_time_trig_edge.data()]) except: - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Pulse time Trigger edge Undefined') + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Pulse time Trigger edge Undefined') raise mdsExceptions.TclFAILED_ESSENTIAL -# Open device +#Open device try: self.initializeInfo() except: - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Cannot open NiSync IEEE1588 device') + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot open NiSync IEEE1588 device') raise mdsExceptions.TclFAILED_ESSENTIAL self.saveInfo() - status = NI6683REC.NiSyncLib.nisync_enable_timestamp_trigger( - self.devFd[0], trigEdge, trigDecCnt) + """ + status = NI6683REC.NiSyncLib.nisync_enable_timestamp_trigger(self.devFd[0], trigEdge, trigDecCnt) print ("self.devFd", self.devFd, status, trigEdge, trigDecCnt) - if status < 0: + + if status < 0 : self.closeInfo() - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Cannot enable pulse time timestamp trigger') + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot enable pulse time timestamp trigger') raise mdsExceptions.TclFAILED_ESSENTIAL for tr in range(8): - if getattr(self, 'trig_%d' % (tr+1)).isOn(): + if getattr(self, 'trig_%d'%(tr+1)).isOn(): try: - trigEdgeName = getattr( - self, 'trig_%d_edge' % (tr+1)).data() + trigEdgeName = getattr(self, 'trig_%d_edge'%(tr+1)).data() trigEdge = c_int(self.trigEdgeDict[trigEdgeName]) except: - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Invalid trigger edge for trigger %s ' % (tr+1)) + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid trigger edge for trigger %s '%(tr+1)) continue - status = NI6683REC.NiSyncLib.nisync_enable_timestamp_trigger( - self.devFd[tr+1], trigEdge, trigDecCnt) - if status < 0: - Data.execute('DevLogErr($1,$2)', self.getNid( - ), 'Cannot enable pulse time timestamp for trigger %d' % (tr+1)) + status = NI6683REC.NiSyncLib.nisync_enable_timestamp_trigger(self.devFd[tr+1], trigEdge, trigDecCnt) + if status < 0 : + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot enable pulse time timestamp for trigger %d'%(tr+1)) continue + """ + return 1 def start(self): try: - self.restoreInfo() + self.restoreInfo() except: - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'SPIDER timing device device not initialized') + Data.execute('DevLogErr($1,$2)', self.getNid(), 'SPIDER timing device device not initialized') raise mdsExceptions.TclFAILED_ESSENTIAL -# Module in acquisition check + try: + trigDecCnt = c_int(self.trig_dec_cnt.data()) + except: + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Trigger decimation count Undefined') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + trigEdge = c_int(self.trigEdgeDict[self.pulse_time_trig_edge.data()]) + except: + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Pulse time Trigger edge Undefined') + raise mdsExceptions.TclFAILED_ESSENTIAL + + status = NI6683REC.NiSyncLib.nisync_enable_timestamp_trigger(self.devFd[0], trigEdge, trigDecCnt) + + print ("self.devFd", self.devFd, status, trigEdge, trigDecCnt) + + + if status < 0 : + self.closeInfo() + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot enable pulse time timestamp trigger') + raise mdsExceptions.TclFAILED_ESSENTIAL + + for tr in range(8): + if getattr(self, 'trig_%d'%(tr+1)).isOn(): + try: + trigEdgeName = getattr(self, 'trig_%d_edge'%(tr+1)).data() + trigEdge = c_int(self.trigEdgeDict[trigEdgeName]) + except: + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid trigger edge for trigger %s '%(tr+1)) + continue + + status = NI6683REC.NiSyncLib.nisync_enable_timestamp_trigger(self.devFd[tr+1], trigEdge, trigDecCnt) + if status < 0 : + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot enable pulse time timestamp for trigger %d'%(tr+1)) + continue + +#Module in acquisition check try: self.restoreWorker() if self.worker.isAlive(): - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Module is in acquisition') - return + Data.execute('DevLogErr($1,$2)', self.getNid(), 'Module is in acquisition') + return except: - pass + pass - self.worker = self.AsynchStore() - self.worker.daemon = True + self.worker = self.AsynchStore() + self.worker.daemon = True self.worker.stopReq = False - self.worker.configure(self) + self.worker.configure(self.copy()) print ("Start Worker") self.saveWorker() self.worker.start() - if not self.worker.isAlive(): - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'SPIDER timing device device not armed') + if not self.worker.isAlive() : + Data.execute('DevLogErr($1,$2)', self.getNid(), 'SPIDER timing device device not armed') raise mdsExceptions.TclFAILED_ESSENTIAL + return 1 + def stop(self): try: self.restoreInfo() except: - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'SPIDER timing device not initialized') + Data.execute('DevLogErr($1,$2)', self.getNid(), 'SPIDER timing device not initialized') raise mdsExceptions.TclFAILED_ESSENTIAL self.restoreWorker() @@ -459,3 +539,5 @@ def stop(self): self.worker.join() print ("Close Info") self.closeInfo() + return 1 + diff --git a/pydevices/RfxDevices/NI_WAVE_GEN.py b/pydevices/RfxDevices/NI_WAVE_GEN.py index 71926c3b3b..b33851f70c 100644 --- a/pydevices/RfxDevices/NI_WAVE_GEN.py +++ b/pydevices/RfxDevices/NI_WAVE_GEN.py @@ -54,6 +54,31 @@ class NI_WAVE_GEN(Device): AO_DAC_POLARITY_UNIPOLAR = c_int(0) AO_DAC_POLARITY_BIPOLAR = c_int(1) + + + XSERIES_AO_EXTERNAL_GATE_DISABLED = c_int(0) + XSERIES_AO_POLARITY_RISING_EDGE = c_int(0) + XSERIES_AO_POLARITY_FALLING_EDGE = c_int(1) + XSERIES_AO_START_TRIGGER_SW_PULSE = c_int(0) + XSERIES_AO_START_TRIGGER_PFI0 = c_int(1) + XSERIES_AO_START_TRIGGER_PFI1 = c_int(2) + XSERIES_AO_START_TRIGGER_PFI2 = c_int(3) + XSERIES_AO_START_TRIGGER_PFI3 = c_int(4) + XSERIES_OUTTIMER_UPDATE_INTERVAL_COUNTER_TB3 = c_int(0) #100MHz + XSERIES_OUTTIMER_UPDATE_INTERVAL_COUNTER_PFI0 = c_int(1) + XSERIES_OUTTIMER_UPDATE_INTERVAL_COUNTER_PFI1 = c_int(2) + XSERIES_OUTTIMER_UPDATE_INTERVAL_COUNTER_PFI2 = c_int(3) + XSERIES_OUTTIMER_UPDATE_INTERVAL_COUNTER_PFI3 = c_int(4) + XSERIES_OUTTIMER_POLARITY_RISING_EDGE = c_int(0) + XSERIES_OUTTIMER_POLARITY_FALLING_EDGE = c_int(1) + XSERIES_OUTPUT_RANGE_10V = c_int(0) + XSERIES_OUTPUT_RANGE_5V = c_int(1) + XSERIES_START_TRIGGER = c_int(2) + XSERIES_AO_UPDATE_COUNTER_UI_TC = c_int(0) + XSERIES_AO_UPDATE_COUNTER_PFI0 = c_int(1) + XSERIES_AO_UPDATE_COUNTER_PFI1 = c_int(2) + XSERIES_AO_UPDATE_COUNTER_PFI2 = c_int(3) + XSERIES_AO_UPDATE_COUNTER_PFI3 = c_int(4) # File descriptor #ao_fd = 0 @@ -64,11 +89,11 @@ class NI_WAVE_GEN(Device): waveAOChFds = {} updateEvents = {} niLib6259 = None - niLib6368 = None + niLibXseries = None niInterfaceLib = None MIN_FREQ = 0.01 - MAX_FREQ = 1000. + MAX_FREQ = 100000. #Dictionaries and maps @@ -97,6 +122,8 @@ def saveInfo(self): def restoreInfo(self, openFlag): if NI_WAVE_GEN.niLib6259 is None: NI_WAVE_GEN.niLib6259 = CDLL("libpxi6259.so") + if NI_WAVE_GEN.niLibXseries is None: + NI_WAVE_GEN.niLibXseries = CDLL("libnixseries.so") if NI_WAVE_GEN.niInterfaceLib is None: NI_WAVE_GEN.niInterfaceLib = CDLL("libNiInterface.so") @@ -126,9 +153,9 @@ def restoreInfo(self, openFlag): boardId)+'.ao' self.ao_fd = os.open(fileName, os.O_RDWR | os.O_NONBLOCK) print('Open fileName : ', fileName) - except IOError(error, message): - print (error, repr(message)) - print (errno.errorcode[error]) + except IOError as e: + print( 'IOError : %s'%(str(e)) ) + return NI_WAVE_GEN.ERROR except Exception as exc: Data.execute('DevLogErr($1,$2)', self.getNid( ), 'Cannot open device ' + fileName + " " + str(exc)) @@ -143,7 +170,7 @@ def closeInfo(self): self.ao_fd = -1 except: pass - #print('CLOSE INFO: HANDLE NOT FOUND') + print('CLOSE INFO: HANDLE NOT FOUND') return 1 # Update Event Management @@ -190,26 +217,35 @@ def run(self): print("Event %s occurred at %s with data: %s " % (str(self.event), str(self.qtime.date), str(self.raw))) jcmd = self.raw.deserialize() - print (jcmd) + #print (jcmd) cmdEventName = self.device.cmd_event.data() + boardType = self.device.board_type.data() if jcmd["command"] == 'pause': try: - self.device.__stopGeneration__() + boardType = self.device.board_type.data() + wavePoint = self.device.wave_point.data() + self.device.__initialize_module__(boardType, wavePoint, True) + self.device.__stopGeneration__() except Exception as ex: + time.sleep(1) Event.setevent(cmdEventName+'_REPLY', 'Cannot pause waveform generation : '+str(ex)) + return elif jcmd["command"] == 'resume': try: - self.device.configChannels(False) + boardType = self.device.board_type.data() + wavePoint = self.device.wave_point.data() + self.device.__initialize_module__(boardType, wavePoint, False) self.device.__startGeneration__() except Exception as ex: + time.sleep(1) Event.setevent(cmdEventName+'_REPLY', 'Cannot resume waveform generation : '+str(ex)) + return elif jcmd["command"] == 'update': boardId = self.device.board_id.data() - boardType = self.device.board_type.data() wavePoint = self.device.wave_point.data() gain = self.device.gain.data() @@ -230,7 +266,20 @@ def run(self): numPeriod = (np.asarray(chFreqAr) / minFreq + 0.5).astype(int) sampleRate = wavePoint * minFreq - periodDivisor = int(20000000 / sampleRate) + + if boardType == 'NI6259': + factor = 20000000 + else: + factor = 100000000 + + periodDivisor = int(factor / sampleRate) + """ + while periodDivisor < 20 : + wavePoint -= 10 + sampleRate = wavePoint * minFreq + periodDivisor = int(factor / sampleRate) + """ + print ('==update periodDivisor ', periodDivisor) print ('==update Num Period ', chFreqAr, numPeriod, minFreq) @@ -244,12 +293,14 @@ def run(self): self.device.saveInfo() aoConfig = c_void_p(0) - NI_WAVE_GEN.niInterfaceLib.pxi6259_create_ao_conf_ptr( - byref(aoConfig)) - - # initialize AO configuration - self.device.__aoConfiguration__( - aoConfig, self.device.AO_DAC_POLARITY_BIPOLAR, wavePoint, periodDivisor) + if boardType == 'NI6259': + NI_WAVE_GEN.niInterfaceLib.pxi6259_create_ao_conf_ptr(byref(aoConfig)) + #initialize AO configuration + self.device.__aoConfiguration_6259__(aoConfig, self.device.AO_DAC_POLARITY_BIPOLAR, wavePoint, periodDivisor) + else : + NI_WAVE_GEN.niInterfaceLib.nixseries_create_ao_conf_ptr(byref(aoConfig), c_int(wavePoint) ) + #initialize AO configuration + self.device.__aoConfiguration_xseries__(aoConfig, self.device.AO_DAC_POLARITY_BIPOLAR, wavePoint, periodDivisor) for ch in range(4): self.device.configChannel(boardType, boardId, ch, False, wavePoint, chMaxAr[ch], chMinAr[ch], chTypeAr[ch].strip( @@ -258,22 +309,26 @@ def run(self): self.device.__startGeneration__() except Exception as ex: + time.sleep(1) Event.setevent( cmdEventName+'_REPLY', 'Cannot update waveforms generation : '+str(ex)) - + return + + print('Generate REPLY event ' + cmdEventName+'_REPLY') + time.sleep(1) Event.setevent(cmdEventName+'_REPLY', msg) return def stop(self): self.stopReq = True - NI6259AI.niInterfaceLib.setStopAcqFlag(self.stopAcq) + NI_WAVE_GEN.niInterfaceLib.setStopAcqFlag(self.stopAcq) def hasError(self): return (self.error != self.ACQ_NOERROR) def closeTree(self): # On first test dosen't work - NI6259AI.niInterfaceLib.closeTree(self.treePtr) + NI_WAVE_GEN.niInterfaceLib.closeTree(self.treePtr) self.device.debugPrint('CLOSE TREE') # End Inner class AsynchStore @@ -356,18 +411,24 @@ def configChannel(self, boardType, boardId, ch, reset, wavePoint, chMax, chMin, ), "Invalid waveform type -%s- for channel %d " % (chType, ch)) zero_arr = np.zeros(wavePoint) scaledWriteArray = (c_float * len(zero_arr))(*zero_arr) + + print(scaledWriteArray[100:110], wavePoint) - retval = NI_WAVE_GEN.niLib6259.pxi6259_write_ao( - aoChFd, scaledWriteArray, c_uint(wavePoint)) - if retval != wavePoint: - errno = NI_WAVE_GEN.niInterfaceLib.getErrno() - Data.execute('DevLogErr($1,$2)', self.getNid( - ), "Failed while writing! Written samples %d : %s (%d)" % (retval, os.strerror(errno), errno)) - raise mdsExceptions.DevIO_STUCK + if boardType == 'NI6259' : + retval = NI_WAVE_GEN.niLib6259.pxi6259_write_ao(aoChFd, scaledWriteArray, c_uint(wavePoint)) + else : + retval = NI_WAVE_GEN.niLibXseries.xseries_write_ao(aoChFd, scaledWriteArray, c_uint(wavePoint)) + + if retval < 0 : + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid( + ), "Failed while writing! Written samples %d : %s (%d)" % (retval, os.strerror(errno), errno)) + raise mdsExceptions.DevIO_STUCK os.close(aoChFd) - def __checkChanneParam__(self, ch, gain): + + def __checkChannelParams__(self, ch, gain): chAOX = [] chAOY = [] @@ -460,12 +521,86 @@ def configChannels(self, reset): print ('Num Period ', freq, numPeriod, minFreq) for ch in range(4): - self.__checkChanneParam__(ch, gain) + self.__checkChannelParams__(ch, gain) self.configChannel(boardType, boardId, ch, reset, wavePoint, self.chMax, self.chMin, self.chType, self.chAOX, self.chAOY, numPeriod[ch]) - def __aoConfiguration__(self, aoConfig, polarity, wavePoint, periodDivisor): + + def __aoConfiguration_xseries__(self, aoConfig, polarity, wavePoint, periodDivisor): + + + print( '__aoConfiguration_xseries__', wavePoint, periodDivisor) + + # Disable external gating of the sample clock + if NI_WAVE_GEN.niLibXseries.xseries_set_ao_external_gate( aoConfig, + self.XSERIES_AO_EXTERNAL_GATE_DISABLED, # No external pause signal + self.XSERIES_AO_POLARITY_RISING_EDGE, # Don't care + c_int(0)) != 0 : # Disable + + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to set AO waveform generation!") + raise mdsExceptions.DevCANNOT_LOAD_SETTINGS + + + + #Program the START1 signal (start trigger) to assert from a software rising edge + if NI_WAVE_GEN.niLibXseries.xseries_set_ao_start_trigger( aoConfig, + self.XSERIES_AO_START_TRIGGER_SW_PULSE, # Set the line to software-driven + self.XSERIES_AO_POLARITY_RISING_EDGE, # Make line active on rising... + c_int(1)) != 0 : # ...edge (not high level) + + + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Error setting start trigger!") + raise mdsExceptions.DevCANNOT_LOAD_SETTINGS + + + #Program the Update source + if NI_WAVE_GEN.niLibXseries.xseries_set_ao_update_counter( aoConfig, + self.XSERIES_AO_UPDATE_COUNTER_UI_TC, # Derive the clock line from the Update + # Interval Terminal Count + self.XSERIES_AO_POLARITY_RISING_EDGE) != 0 : # Make the line active on rising edge + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Error setting update counter!") + raise mdsExceptions.DevCANNOT_LOAD_SETTINGS + + #Program the Update Interval counter */ + print('periodDivisor', periodDivisor) + if NI_WAVE_GEN.niLibXseries.xseries_set_ao_update_interval_counter( aoConfig, + self.XSERIES_OUTTIMER_UPDATE_INTERVAL_COUNTER_TB3, # Source the Update + # Interval from the + # internal timebase + self.XSERIES_OUTTIMER_POLARITY_RISING_EDGE, # Make the line active on rising + # edge + c_uint(periodDivisor), # Number of clock intervals between successive + # updates + c_int(2) # Number of clock intervals after the start trigger before the first + # update + ) != 0 : + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Error setting update interval counter!") + raise mdsExceptions.DevCANNOT_LOAD_SETTINGS + + for ch in range(4): + if NI_WAVE_GEN.niLibXseries.xseries_add_ao_channel(aoConfig, c_int(ch), self.XSERIES_OUTPUT_RANGE_10V) != 0 : + Data.execute('DevLogErr($1,$2)', self.getNid(), + 'Cannot add AI channel %d to configuration!'%(ch)) + raise mdsExceptions.DevCANNOT_LOAD_SETTINGS + + # load configuration to the device + #if NI_WAVE_GEN.niLibXseries.xseries_load_ao_conf(c_int(self.ao_fd), aoConfig) != 0 : + if NI_WAVE_GEN.niInterfaceLib.nixseries_load_ao_conf_ptr(c_int(self.ao_fd), aoConfig) != 0 : + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid( + ), 'Failed to load configuration! (%d) %s' % (errno, os.strerror(errno))) + raise mdsExceptions.DevCANNOT_LOAD_SETTINGS + + # wait for the AO devices + time.sleep(1) + + + def __aoConfiguration_6259__(self, aoConfig, polarity, wavePoint, periodDivisor): # enable waveform generation (Retrasmit mode) if NI_WAVE_GEN.niLib6259.pxi6259_set_ao_waveform_generation(aoConfig, c_ubyte(1)): @@ -508,40 +643,149 @@ def __aoConfiguration__(self, aoConfig, polarity, wavePoint, periodDivisor): time.sleep(1) - def init(self): - print ('================= NI Wavefor Generation Init ===============') + def __initialize_module__(self, boardType, wavePoint, reset): - if self.board_type.data() == 'NI6368': - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Device NI6368 not yet supported') - raise mdsExceptions.DevINV_SETUP + # configure AO update clock + freq = [] + for ch in range(4): + if getattr(self, 'ao_%d' % (ch+1)).isOn(): + try: + fr = getattr(self, 'ao_%d_freq' % (ch+1)).data() + freq.append(fr) + except Exception as ex: + Data.execute('DevLogErr($1,$2)', self.getNid( + ), 'Invalid channel %d waveform frequency : %s' % (ch, str(ex))) + raise mdsExceptions.TclFAILED_ESSENTIAL + if fr < (self.MIN_FREQ - 1e-6) or fr > (self.MAX_FREQ + 1e-4): + Data.execute('DevLogErr($1,$2)', self.getNid( + ), 'Invalid channel %d waveform frequency %f out of limit (%0.2f:%0.2f)' % (ch, fr, self.MIN_FREQ, self.MAX_FREQ)) + raise mdsExceptions.DevBAD_FREQ - if self.restoreInfo(True) == NI_WAVE_GEN.ERROR: - Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Cannot open device') - raise mdsExceptions.DevINV_SETUP + minFreq = min(freq) + print ("Frequency ", freq) + print ((np.asarray(freq)*10).astype(int) % int(minFreq*10)) + + if sum((np.asarray(freq)*10).astype(int) % int(minFreq*10)): + Data.execute('DevLogErr($1,$2)', self.getNid( + ), 'Minimum waveform frequency must be multiple of the other wavefoms frequency') + raise mdsExceptions.DevBAD_FREQ - # Stop the segment - """ - NI_WAVE_GEN.niLib6259.xseries_stop_ao(c_int(self.ao_fd)) + """ + self.numPeriod = (np.asarray(freq) / minFreq + 0.5).astype(int) + print 'Num Period ',self.numPeriod + """ - retval = NI_WAVE_GEN.niLib6259.xseries_reset_ao(self.ao_fd); - if retval : - Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error resetiing device') - raise mdsExceptions.TclFAILED_ESSENTIAL - - retval = NI_WAVE_GEN.niLib6259.pxi6259_stop_ao(c_int(self.ao_fd)) - if retval : - Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error resetting device') - raise mdsExceptions.TclFAILED_ESSENTIAL + wavePoint = 4000 + + """ + currWavePoint = wavePoint + ch = 0 + for c in range(0, 4): + if getattr(self, 'ao_%d' % (c+1)).isOn(): + fr = freq[ch] + if freq[ch] < 1.: + fr = freq[ch] * 10. + if wavePoint % freq[ch]: + wp = int(int(float(wavePoint) / fr) * fr + fr) + if wp % 2: + wp = wp + fr + if wp > currWavePoint: + currWavePoint = wp + print (currWavePoint, wavePoint, freq[ch]) + + #if ( wavePoint / freq[ch] ) < 10. : + # Data.execute('DevLogErr($1,$2)', self.getNid(), 'Waveform %d has less than 10 points for period'%(ch)) + # raise mdsExceptions.TclFAILED_ESSENTIAL; + + ch = ch + 1 - retval = NI_WAVE_GEN.niLib6259.pxi6259_reset_ao(c_int(self.ao_fd)); - if retval : - Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error resetting device') - raise mdsExceptions.TclFAILED_ESSENTIAL + if currWavePoint != wavePoint: + wavePoint = currWavePoint + self.wave_point.putData(wavePoint) + """ + + sampleRate = wavePoint * minFreq + """ + if boardType == 'NI6259': + periodDivisor = int(20000000 / sampleRate) + else: + periodDivisor = int(100000000 / sampleRate) + + """ + if boardType == 'NI6259': + factor = 20000000 + else: + factor = 100000000 + + sampleInPeriod = int( factor / minFreq ) + numPeriod = int(wavePoint / sampleInPeriod) + + print('sampleInPeriod', sampleInPeriod) + print('numPeriod', numPeriod) + print('minFreq', minFreq) + + periodDivisor = int(factor / sampleRate) + + while periodDivisor < 30 : + wavePoint -= 10 + sampleRate = wavePoint * minFreq + periodDivisor = factor / sampleRate + #print('periodDivisor ', periodDivisor, wavePoint) + + + print ('periodDivisor ', periodDivisor) + print ('wavePoint ', wavePoint) + + self.wave_point.putData(wavePoint) + + aoConfig = c_void_p(0) + if boardType == 'NI6259': + NI_WAVE_GEN.niInterfaceLib.pxi6259_create_ao_conf_ptr(byref(aoConfig)) + else : + if NI_WAVE_GEN.niLibXseries.xseries_stop_ao(c_int(self.ao_fd)) != 0: + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to stop AO!: %s" % (os.strerror(errno))) + + if NI_WAVE_GEN.niLibXseries.xseries_reset_ao(c_int(self.ao_fd)) != 0: + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to reset AO!: %s" % (os.strerror(errno))) + + NI_WAVE_GEN.niInterfaceLib.nixseries_create_ao_conf_ptr(byref(aoConfig), c_int(wavePoint) ) + + # initialize AO configuration + if boardType == 'NI6259': + self.__aoConfiguration_6259__(aoConfig, self.AO_DAC_POLARITY_BIPOLAR, wavePoint, periodDivisor) + else: + self.__aoConfiguration_xseries__(aoConfig, self.AO_DAC_POLARITY_BIPOLAR, wavePoint, periodDivisor) + + self.configChannels(reset) + + if boardType == 'NI6259': + NI_WAVE_GEN.niInterfaceLib.pxi6259_free_ao_conf_ptr(aoConfig) + else: + NI_WAVE_GEN.niInterfaceLib.nixseries_free_ai_conf_ptr(aoConfig) + + + def init(self): + + print ('================= NI Waveform Generation Init ===============') + + if self.restoreInfo(True) == NI_WAVE_GEN.ERROR: + Data.execute('DevLogErr($1,$2)', self.getNid(), + 'Cannot open device') + raise mdsExceptions.DevINV_SETUP + + try: + boardType = self.board_type.data() + except Exception as ex: + Data.execute('DevLogErr($1,$2)', self.getNid(), + 'Board Type parameter undefined') + raise mdsExceptions.DevBAD_PARAMETER try: wavePoint = self.wave_point.data() @@ -549,7 +793,10 @@ def init(self): Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid waveform points number') raise mdsExceptions.DevBAD_PARAMETER + + self.__initialize_module__(boardType, wavePoint, False) + """ # configure AO update clock freq = [] for ch in range(4): @@ -575,10 +822,10 @@ def init(self): ), 'Minimum waveform frequency must be multiple of the other wavefoms frequency') raise mdsExceptions.DevBAD_FREQ - """ - self.numPeriod = (np.asarray(freq) / minFreq + 0.5).astype(int) - print 'Num Period ',self.numPeriod - """ + + #self.numPeriod = (np.asarray(freq) / minFreq + 0.5).astype(int) + #print 'Num Period ',self.numPeriod + currWavePoint = wavePoint ch = 0 @@ -595,11 +842,11 @@ def init(self): currWavePoint = wp print (currWavePoint, wavePoint, freq[ch]) - """ - if ( wavePoint / freq[ch] ) < 10. : - Data.execute('DevLogErr($1,$2)', self.getNid(), 'Waveform %d has less than 10 points for period'%(ch)) - raise mdsExceptions.TclFAILED_ESSENTIAL; - """ + + #if ( wavePoint / freq[ch] ) < 10. : + # Data.execute('DevLogErr($1,$2)', self.getNid(), 'Waveform %d has less than 10 points for period'%(ch)) + # raise mdsExceptions.TclFAILED_ESSENTIAL; + ch = ch + 1 if currWavePoint != wavePoint: @@ -607,34 +854,48 @@ def init(self): self.wave_point.putData(wavePoint) sampleRate = wavePoint * minFreq - periodDivisor = int(20000000 / sampleRate) + if boardType == 'NI6259': + periodDivisor = int(20000000 / sampleRate) + else: + periodDivisor = int(100000000 / sampleRate) + print ('periodDivisor ', periodDivisor) print ('OK 1') aoConfig = c_void_p(0) - NI_WAVE_GEN.niInterfaceLib.pxi6259_create_ao_conf_ptr(byref(aoConfig)) + if boardType == 'NI6259': + NI_WAVE_GEN.niInterfaceLib.pxi6259_create_ao_conf_ptr(byref(aoConfig)) + else : + if NI_WAVE_GEN.niLibXseries.xseries_stop_ao(c_int(self.ao_fd)) != 0: + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to stop AO!: %s" % (os.strerror(errno))) + + if NI_WAVE_GEN.niLibXseries.xseries_reset_ao(c_int(self.ao_fd)) != 0: + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to reset AO!: %s" % (os.strerror(errno))) + + NI_WAVE_GEN.niInterfaceLib.nixseries_create_ao_conf_ptr(byref(aoConfig), c_int(wavePoint) ) print ('OK 2') # initialize AO configuration - self.__aoConfiguration__( - aoConfig, self.AO_DAC_POLARITY_BIPOLAR, wavePoint, periodDivisor) - - print ('OK 3') + if boardType == 'NI6259': + self.__aoConfiguration_6259__(aoConfig, self.AO_DAC_POLARITY_BIPOLAR, wavePoint, periodDivisor) + else: + self.__aoConfiguration_xseries__(aoConfig, self.AO_DAC_POLARITY_BIPOLAR, wavePoint, periodDivisor) self.configChannels(False) - print ('OK 4') - - NI_WAVE_GEN.niInterfaceLib.pxi6259_free_ao_conf_ptr(aoConfig) - - print ('OK 5') - + if boardType == 'NI6259': + NI_WAVE_GEN.niInterfaceLib.pxi6259_free_ao_conf_ptr(aoConfig) + else: + NI_WAVE_GEN.niInterfaceLib.nixseries_free_ai_conf_ptr(aoConfig) + """ + self.saveInfo() - - print ('OK 6') - return NI_WAVE_GEN.NO_ERROR @@ -645,18 +906,32 @@ def __startGeneration__(self): Data.execute('DevLogErr($1,$2)', self.getNid(), 'Module not initialized') raise mdsExceptions.DevINV_SETUP + + boardType = self.board_type.data() # start AO segment (signal generation) - if NI_WAVE_GEN.niLib6259.pxi6259_start_ao(c_int(self.ao_fd)) != 0: - errno = NI_WAVE_GEN.niInterfaceLib.getErrno() - Data.execute('DevLogErr($1,$2)', self.getNid(), - "Failed to start AO!: %s" % (os.strerror(errno))) - raise mdsExceptions.DevIO_STUCK + if boardType == 'NI6259' : + if NI_WAVE_GEN.niLib6259.pxi6259_start_ao(c_int(self.ao_fd)) != 0: + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to start AO!: %s" % (os.strerror(errno))) + raise mdsExceptions.DevIO_STUCK + else: + if NI_WAVE_GEN.niLibXseries.xseries_start_ao(c_int(self.ao_fd)) != 0: + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to start AO!: %s" % (os.strerror(errno))) + # pulse start trigger + if NI_WAVE_GEN.niLibXseries.xseries_pulse_ao(self.ao_fd, self.XSERIES_START_TRIGGER) != 0: + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to software trigger: %s" % (os.strerror(errno))) + raise mdsExceptions.DevIO_STUCK return NI_WAVE_GEN.NO_ERROR def start_gen(self): - print ("================ NI Waveform Geneation Start Store =============") + print ("================ NI Waveform Generation Start =============") self.__startGeneration__() @@ -668,21 +943,48 @@ def start_gen(self): raise mdsExceptions.DevBAD_PARAMETER self.updEvent = self.AsynchUpdateGen(cmdEventName) - self.updEvent.configure(self) + self.updEvent.configure(self.copy()) self.saveUpdateEvent() return NI_WAVE_GEN.NO_ERROR # Stop generation + # private method + def __stopGeneration__(self): - + if self.restoreInfo(False) != NI_WAVE_GEN.HANDLE_FOUND: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Module not initialized') raise mdsExceptions.DevINV_SETUP + boardType = self.board_type.data() + + if boardType == 'NI6259' : + self.__stopGeneration_6259__() + else: + self.__stopGeneration_xseries__() + if NI_WAVE_GEN.niLibXseries.xseries_reset_ao(c_int(self.ao_fd)) != 0: + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to reset AO!: %s" % (os.strerror(errno))) + + + def __stopGeneration_xseries__(self): + + # stop AO segment + if NI_WAVE_GEN.niLibXseries.xseries_stop_ao(c_int(self.ao_fd)) != 0: + errno = NI_WAVE_GEN.niInterfaceLib.getErrno() + Data.execute('DevLogErr($1,$2)', self.getNid(), + "Failed to stop AO!: %s" % (os.strerror(errno))) + raise mdsExceptions.DevIO_STUCK + + + # private method + def __stopGeneration_6259__(self): + # stop AO segment if NI_WAVE_GEN.niLib6259.pxi6259_stop_ao(c_int(self.ao_fd)) != 0: errno = NI_WAVE_GEN.niInterfaceLib.getErrno() @@ -690,7 +992,7 @@ def __stopGeneration__(self): "Failed to stop AO!: %s" % (os.strerror(errno))) raise mdsExceptions.DevIO_STUCK - self.configChannels(True) + self.configChannels(True) #Configure output to generate 0V # start AO segment (signal generation) if NI_WAVE_GEN.niLib6259.pxi6259_start_ao(self.ao_fd): @@ -706,15 +1008,23 @@ def __stopGeneration__(self): raise mdsExceptions.DevIO_STUCK def stop_gen(self): - print ("================ NI Waveform Geneation Stop Store =============") - - self.__stopGeneration__() - + print ("================ NI Waveform Generation Stop =============") + if self.restoreInfo(False) != NI_WAVE_GEN.HANDLE_FOUND: Data.execute('DevLogErr($1,$2)', self.getNid(), - 'Wavefor generation not initialized') + 'Module not initialized') raise mdsExceptions.DevINV_SETUP + boardType = self.board_type.getData() + + if boardType == 'NI6259' : + self.__stopGeneration_6259__() + else: + boardType = self.board_type.data() + wavePoint = self.wave_point.data() + self.__initialize_module__(boardType, wavePoint, True) + self.__stopGeneration__() + self.closeInfo() if self.closeUpdateEvent() == NI_WAVE_GEN.ERROR: @@ -741,7 +1051,8 @@ def __cmdEvent__(self, cmd): Event.setevent(cmdEventName, cmd) rep = self.waitForAnswer(cmdEventName+'_REPLY') - timeout = 5 + timeout = 10 + print('Wait for REPLY event ' + cmdEventName+'_REPLY') rep.join(timeout) time.sleep(.1) if rep.isAlive(): @@ -775,7 +1086,7 @@ def update_gen(self): gain = self.gain.data() for ch in range(4): - self.__checkChanneParam__(ch, gain) + self.__checkChannelParams__(ch, gain) chStateAr.append(self.chState) chMaxAr.append(self.chMax) diff --git a/pydevices/RfxDevices/PTGREY.py b/pydevices/RfxDevices/PTGREY.py index ff6f96885c..6ac9858d5a 100755 --- a/pydevices/RfxDevices/PTGREY.py +++ b/pydevices/RfxDevices/PTGREY.py @@ -1,4 +1,4 @@ -# +# # Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. # # Redistribution and use in source and binary forms, with or without @@ -23,68 +23,66 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -from MDSplus import mdsExceptions, Device, Data, version +from MDSplus import mdsExceptions, Device, Data, version, Float64 from ctypes import CDLL, byref, c_double, c_int, c_float, c_void_p, c_char_p, create_string_buffer from numpy import array from threading import Thread import traceback - +import time class PTGREY(Device): """PTGREY NEW Camera""" - parts = [ # offset nid - {'path': ':IP_NAME', 'type': 'text', 'value': '192.168.100.18'}, # 1 - {'path': ':COMMENT', 'type': 'text'}, - - {'path': '.FRAME', 'type': 'structure'}, # 3 - {'path': '.FRAME:X', 'type': 'numeric', 'value': 0}, - {'path': '.FRAME:Y', 'type': 'numeric', 'value': 0}, - {'path': '.FRAME:WIDTH', 'type': 'numeric', 'value': 1936}, - {'path': '.FRAME:HEIGHT', 'type': 'numeric', 'value': 1464}, - {'path': '.FRAME:PIXEL_FORMAT', 'type': 'text', 'value': 'Mono16'}, - - {'path': '.CAM_SETUP', 'type': 'structure'}, # 9 - {'path': '.CAM_SETUP:GAIN_AUTO', 'type': 'text', 'value': 'Off'}, - {'path': '.CAM_SETUP:GAIN', 'type': 'numeric', 'value': 0}, - {'path': '.CAM_SETUP:GAMMA_EN', 'type': 'text', 'value': 'Off'}, - {'path': '.CAM_SETUP:EXP_AUTO', 'type': 'text', 'value': 'Off'}, - {'path': '.CAM_SETUP:EXPOSURE', 'type': 'numeric', 'value': 800E3}, - - {'path': '.TIMING', 'type': 'structure'}, # 15 - {'path': '.TIMING:TRIG_MODE', 'type': 'text', 'value': 'INTERNAL'}, - {'path': '.TIMING:TRIG_SOURCE', 'type': 'numeric'}, - {'path': '.TIMING:TIME_BASE', 'type': 'numeric'}, - {'path': '.TIMING:FRAME_RATE', 'type': 'numeric', 'value': 1}, - {'path': '.TIMING:BURST_DUR', 'type': 'numeric', 'value': 5}, - {'path': '.TIMING:SKIP_FRAME', 'type': 'numeric', 'value': 0}, - - {'path': '.STREAMING', 'type': 'structure'}, # 22 - {'path': '.STREAMING:MODE', 'type': 'text', 'value': 'Stream and Store'}, - {'path': '.STREAMING:SERVER', 'type': 'text', 'value': 'localhost'}, - {'path': '.STREAMING:PORT', 'type': 'numeric', 'value': 8888}, - {'path': '.STREAMING:AUTOSCALE', 'type': 'text', 'value': 'NO'}, - {'path': '.STREAMING:LOLIM', 'type': 'numeric', 'value': 0}, - {'path': '.STREAMING:HILIM', 'type': 'numeric', 'value': 4095}, - {'path': '.STREAMING:ADJROIX', 'type': 'numeric', 'value': 0}, - {'path': '.STREAMING:ADJROIY', 'type': 'numeric', 'value': 0}, - {'path': '.STREAMING:ADJROIW', 'type': 'numeric', 'value': 1936}, - {'path': '.STREAMING:ADJROIH', 'type': 'numeric', 'value': 1464}, - - {'path': ':FRAMES', 'type': 'signal', 'options': ( - 'no_write_model', 'no_compress_on_put')}, - {'path': ':FRAMES_METAD', 'type': 'signal', 'options': ( - 'no_write_model', 'no_compress_on_put')}, - {'path': ':FRAME0_TIME', 'type': 'numeric', 'value': 0}] - - parts.append({'path': ':INIT_ACT', 'type': 'action', - 'valueExpr': "Action(Dispatch('CAMERA_SERVER','PULSE_PREPARATION',50,None),Method(None,'init',head))", - 'options': ('no_write_shot',)}) - parts.append({'path': ':START_ACT', 'type': 'action', - 'valueExpr': "Action(Dispatch('CAMERA_SERVER','INIT',50,None),Method(None,'startAcquisition',head))", - 'options': ('no_write_shot',)}) - parts.append({'path': ':STOP_ACT', 'type': 'action', - 'valueExpr': "Action(Dispatch('CAMERA_SERVER','STORE',50,None),Method(None,'stopAcquisition',head))", - 'options': ('no_write_shot',)}) + parts=[ #offset nid + {'path':':IP_NAME', 'type':'text', 'value':'192.168.100.18'}, #1 + {'path':':COMMENT', 'type':'text'}, + + {'path':'.FRAME', 'type':'structure'}, #3 + {'path':'.FRAME:X', 'type':'numeric', 'value':0}, + {'path':'.FRAME:Y', 'type':'numeric', 'value':0}, + {'path':'.FRAME:WIDTH', 'type':'numeric', 'value':1936}, + {'path':'.FRAME:HEIGHT', 'type':'numeric', 'value':1464}, + {'path':'.FRAME:PIXEL_FORMAT', 'type':'text', 'value':'Mono16'}, + + {'path':'.CAM_SETUP', 'type':'structure'}, #9 + {'path':'.CAM_SETUP:GAIN_AUTO', 'type':'text', 'value':'Off'}, + {'path':'.CAM_SETUP:GAIN', 'type':'numeric', 'value':0}, + {'path':'.CAM_SETUP:GAMMA_EN', 'type':'text', 'value':'Off'}, + {'path':'.CAM_SETUP:EXP_AUTO', 'type':'text', 'value':'Off'}, + {'path':'.CAM_SETUP:EXPOSURE', 'type':'numeric', 'value':800E3}, + + {'path':'.TIMING', 'type':'structure'}, #15 + {'path':'.TIMING:TRIG_MODE', 'type':'text', 'value':'INTERNAL'}, + {'path':'.TIMING:TRIG_SOURCE', 'type':'numeric'}, + {'path':'.TIMING:TIME_BASE', 'type':'numeric'}, + {'path':'.TIMING:FRAME_RATE', 'type':'numeric', 'value':1}, + {'path':'.TIMING:BURST_DUR', 'type':'numeric', 'value':5}, + {'path':'.TIMING:SKIP_FRAME', 'type':'numeric', 'value':0}, + + {'path':'.STREAMING', 'type':'structure'}, #22 + {'path':'.STREAMING:MODE', 'type':'text', 'value':'Stream and Store'}, + {'path':'.STREAMING:SERVER', 'type':'text', 'value':'localhost'}, + {'path':'.STREAMING:PORT', 'type':'numeric', 'value':8888}, + {'path':'.STREAMING:AUTOSCALE', 'type':'text', 'value':'NO'}, + {'path':'.STREAMING:LOLIM', 'type':'numeric', 'value':0}, + {'path':'.STREAMING:HILIM', 'type':'numeric', 'value':4095}, + {'path':'.STREAMING:ADJROIX', 'type':'numeric', 'value':0}, + {'path':'.STREAMING:ADJROIY', 'type':'numeric', 'value':0}, + {'path':'.STREAMING:ADJROIW', 'type':'numeric', 'value':1936}, + {'path':'.STREAMING:ADJROIH', 'type':'numeric', 'value':1464}, + + {'path':':FRAMES', 'type':'signal','options':('no_write_model', 'no_compress_on_put')}, + {'path':':FRAMES_METAD', 'type':'signal','options':('no_write_model', 'no_compress_on_put')}, + {'path':':FRAME0_TIME', 'type':'numeric','value':0}] + + parts.append({'path':':INIT_ACT','type':'action', + 'valueExpr':"Action(Dispatch('CAMERA_SERVER','PULSE_PREPARATION',50,None),Method(None,'init',head))", + 'options':('no_write_shot',)}) + parts.append({'path':':START_ACT','type':'action', + 'valueExpr':"Action(Dispatch('CAMERA_SERVER','INIT',50,None),Method(None,'startAcquisition',head))", + 'options':('no_write_shot',)}) + parts.append({'path':':STOP_ACT','type':'action', + 'valueExpr':"Action(Dispatch('CAMERA_SERVER','STORE',50,None),Method(None,'stopAcquisition',head))", + 'options':('no_write_shot',)}) handle = c_int(-1) handles = {} @@ -96,7 +94,8 @@ class PTGREY(Device): error = create_string_buffer(version.tobytes(''), 512) def debugPrint(self, msg="", obj=""): - print("------ DEBUG " + self.name + ":" + msg, obj) + print( "------ DEBUG " + self.name + ":" + msg, obj ); + """Asynchronous readout internal class""" class AsynchStore(Thread): @@ -110,32 +109,30 @@ def run(self): self.device.debugPrint("Asychronous acquisition thread") - status = PTGREY.ptgreyLib.startFramesAcquisition( - self.device.handle) + status = PTGREY.ptgreyLib.startFramesAcquisition(self.device.handle) if status < 0: - PTGREY.ptgreyLib.getLastError( - self.device.handle, self.device.error) - Data.execute('DevLogErr($1,$2)', self.device.nid, - 'Cannot start frames acquisition : ' + self.device.error.raw) + PTGREY.ptgreyLib.getLastError(self.device.handle, self.device.error) + Data.execute('DevLogErr($1,$2)', self.device.nid, 'Cannot start frames acquisition : ' + self.device.error.raw ) self.device.debugPrint("Acquisition thread ended") self.device.removeInfo() + def stop(self): self.device.debugPrint("STOP frames acquisition loop") status = PTGREY.ptgreyLib.stopFramesAcquisition(self.device.handle) if status < 0: - PTGREY.ptgreyLib.getLastError( - self.device.handle, self.device.error) - Data.execute('DevLogErr($1,$2)', self.device.nid, - 'Cannot stop frames acquisition : ' + self.device.error.raw) + PTGREY.ptgreyLib.getLastError(self.device.handle, self.device.error) + Data.execute('DevLogErr($1,$2)', self.device.nid, 'Cannot stop frames acquisition : ' + self.device.error.raw ) + + def saveWorker(self): PTGREY.workers[self.nid] = self.worker ###save Info### -# saveInfo and restoreInfo allow to manage multiple occurrences of camera devices -# and to avoid opening and closing devices handles +#saveInfo and restoreInfo allow to manage multiple occurrences of camera devices +#and to avoid opening and closing devices handles def saveInfo(self): PTGREY.handles[self.nid] = self.handle @@ -145,251 +142,231 @@ def restoreWorker(self): self.worker = PTGREY.workers[self.nid] return 1 else: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot restore worker!!') + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot restore worker!!') raise mdsExceptions.TclFAILED_ESSENTIAL ###check worker### - def checkWorker(self): # FM 20191114 - if self.nid in PTGREY.workers.keys(): - self.debugPrint('CHECK WORKER: found') - return 1 - else: - self.debugPrint('CHECK WORKER: NOT found') - return 0 + def checkWorker(self): #FM 20191114 + if self.nid in PTGREY.workers.keys(): + self.debugPrint('CHECK WORKER: found') + return 1 + else: + self.debugPrint('CHECK WORKER: NOT found') + return 0 ###check info### - def checkInfo(self): # FM 20191114 - if self.nid in PTGREY.handles.keys(): - self.debugPrint('CHECK INFO: found') - return 1 - else: - self.debugPrint('CHECK INFO: NOT found') - return 0 - - -# restore info### (returned value 0:error 1:camera opened 2:camera was already opened) - def restoreInfo(self): - self.debugPrint("restore Info") + def checkInfo(self): #FM 20191114 + if self.nid in PTGREY.handles.keys(): + self.debugPrint('CHECK INFO: found') + return 1 + else: + self.debugPrint('CHECK INFO: NOT found') + return 0 + + +###restore info### (returned value 0:error 1:camera opened 2:camera was already opened) + def restoreInfo(self): + self.debugPrint("restore Info") + try: + if PTGREY.ptgreyLib is None: + libName = "libptgrey.so" + PTGREY.ptgreyLib = CDLL(libName) + self.debugPrint(obj=PTGREY.ptgreyLib) + if PTGREY.mdsLib is None: + libName = "libcammdsutils.so" + PTGREY.mdsLib = CDLL(libName) + self.debugPrint(obj=PTGREY.mdsLib) + if PTGREY.streamLib is None: + libName = "libcamstreamutils.so" + PTGREY.streamLib = CDLL(libName) + self.debugPrint(obj=PTGREY.streamLib) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot load library : ' + libName ) + raise mdsExceptions.TclFAILED_ESSENTIAL + + if self.checkInfo(): + self.handle = PTGREY.handles[self.nid] + return 2 + else: try: - if PTGREY.ptgreyLib is None: - libName = "libptgrey.so" - PTGREY.ptgreyLib = CDLL(libName) - self.debugPrint(obj=PTGREY.ptgreyLib) - if PTGREY.mdsLib is None: - libName = "libcammdsutils.so" - PTGREY.mdsLib = CDLL(libName) - self.debugPrint(obj=PTGREY.mdsLib) - if PTGREY.streamLib is None: - libName = "libcamstreamutils.so" - PTGREY.streamLib = CDLL(libName) - self.debugPrint(obj=PTGREY.streamLib) + name = self.ip_name.data() except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot load library : ' + libName) - raise mdsExceptions.TclFAILED_ESSENTIAL + Data.execute('DevLogErr($1,$2)', self.nid, 'Missing device name' ) + raise mdsExceptions.TclFAILED_ESSENTIAL - if self.checkInfo(): - self.handle = PTGREY.handles[self.nid] - return 2 - else: - try: - name = self.ip_name.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Missing device name') - raise mdsExceptions.TclFAILED_ESSENTIAL - - self.debugPrint("Opening Camera") - self.handle = c_int(-1) - status = PTGREY.ptgreyLib.PGopen( - c_char_p(name), byref(self.handle)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot open device ' + name + ' ('+self.error.raw+')') - raise mdsExceptions.TclFAILED_ESSENTIAL - self.debugPrint("Connected ", status) + self.debugPrint("Opening Camera") + self.handle = c_int(-1) + status = PTGREY.ptgreyLib.PGopen(c_char_p(name), byref(self.handle)) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot open device '+ name +' ('+self.error.raw+')') + raise mdsExceptions.TclFAILED_ESSENTIAL + self.debugPrint("Connected ", status) - self.saveInfo() + self.saveInfo() - return 1 + return 1 ###remove info### def removeInfo(self): - try: - status = PTGREY.ptgreyLib.PGclose(self.handle) # close camera - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot close camera : ' + self.error.raw) - except: - self.debugPrint('ERROR in ptgreyLib.PGclose()') + try: + status = PTGREY.ptgreyLib.PGclose(self.handle) #close camera + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot close camera : ' + self.error.raw ) + except: + self.debugPrint('ERROR in ptgreyLib.PGclose()') - try: - del(PTGREY.handles[self.nid]) - self.debugPrint('Camera Info removed.') - except: - self.debugPrint('ERROR trying to remove info') + try: + del(PTGREY.handles[self.nid]) + self.debugPrint('Camera Info removed.') + except: + self.debugPrint('ERROR trying to remove info') ###remove worker### def removeWorker(self): - try: - del(PTGREY.workers[self.nid]) - self.debugPrint('Camera Worker removed.') - except: - self.debugPrint('ERROR trying to remove Worker') + try: + del(PTGREY.workers[self.nid]) + self.debugPrint('Camera Worker removed.') + except: + self.debugPrint('ERROR trying to remove Worker') + ##########init############################################################################ def init(self): - if self.checkWorker(): # FM 20191114 - self.debugPrint('Cannot dispatch init during acquisition/storing.') - return 1 - if self.restoreInfo() == 0: - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - self.frames.setCompressOnPut(False) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot disable automatic compress on put for frames node') - raise mdsExceptions.TclFAILED_ESSENTIAL - try: - self.frames_metad.setCompressOnPut(False) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot disable automatic compress on put for frames_metad node') - raise mdsExceptions.TclFAILED_ESSENTIAL - - -# Gain - try: - gain = self.cam_setup_gain.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid gain value') - raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setGain(self.handle, c_float(gain)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Set Gain : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - - -# Gain Auto - try: - gainAuto = self.cam_setup_gain_auto.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid gain auto value') - raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setGainAuto(self.handle, c_char_p(gainAuto)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Set Gain Auto : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - -# Gamma Enable - try: - gammaEnable = self.cam_setup_gamma_en.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid gamma enable value') - raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setGammaEnable( - self.handle, c_char_p(gammaEnable)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Set Gamma Enable : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - - -# Exposure Auto - try: - exposureAuto = self.cam_setup_exp_auto.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid exposure auto value') - raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setExposureAuto( - self.handle, c_char_p(exposureAuto)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Set Exposure Auto : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - -# Exposure - try: - exposure = self.cam_setup_exposure.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid exposure value') - raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setExposure(self.handle, c_float(exposure)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Set Exposure : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - - -# READ CAMERA TEMPERATURE - status = PTGREY.ptgreyLib.readInternalTemperature(self.handle) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Read Internal Temperature : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - - -# Pixel Format - try: - pixelFormat = self.frame_pixel_format.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid pixel format value') - raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setPixelFormat( - self.handle, c_char_p(pixelFormat)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Set Pixel Format : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - - -# Frame Rate - try: - frameRate = self.timing_frame_rate.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid frame rate value') - raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setFrameRate( - self.handle, c_double(frameRate)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Set Frame Rate : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - self.debugPrint('fede4') - - -# Frame Area - try: - x = self.frame_x.data() - y = self.frame_y.data() - width = self.frame_width.data() - height = self.frame_height.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid Frame Area value') - raise mdsExceptions.TclFAILED_ESSENTIAL + if self.checkWorker(): #FM 20191114 + self.debugPrint('Cannot dispatch init during acquisition/storing.') + return 1 + if self.restoreInfo() == 0: + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + self.frames.setCompressOnPut(False) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot disable automatic compress on put for frames node') + raise mdsExceptions.TclFAILED_ESSENTIAL + try: + self.frames_metad.setCompressOnPut(False) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot disable automatic compress on put for frames_metad node') + raise mdsExceptions.TclFAILED_ESSENTIAL + +###Gain Auto + try: + gainAuto = self.cam_setup_gain_auto.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid gain auto value') + raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setGainAuto(self.handle, c_char_p(gainAuto)) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Gain Auto : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + time.sleep(0.1) + +###Gain + try: + gain = self.cam_setup_gain.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid gain value') + raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setGain(self.handle, c_float(gain)) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Gain : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + +###Gamma Enable + try: + gammaEnable = self.cam_setup_gamma_en.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid gamma enable value') + raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setGammaEnable(self.handle, c_char_p(gammaEnable)) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Gamma Enable : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + +###Exposure Auto + try: + exposureAuto = self.cam_setup_exp_auto.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid exposure auto value') + raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setExposureAuto(self.handle, c_char_p(exposureAuto)) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Exposure Auto : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + +###Exposure + try: + exposure = self.cam_setup_exposure.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid exposure value') + raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setExposure(self.handle, c_float(exposure)) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Exposure : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + +###READ CAMERA TEMPERATURE + status = PTGREY.ptgreyLib.readInternalTemperature(self.handle) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Read Internal Temperature : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + +###Pixel Format + try: + pixelFormat = self.frame_pixel_format.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid pixel format value') + raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setPixelFormat(self.handle, c_char_p(pixelFormat)) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Pixel Format : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + +###Frame Rate + try: + fRate = self.timing_frame_rate.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid frame rate value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + frameRate = c_double(fRate) + status = PTGREY.ptgreyLib.setFrameRate(self.handle, byref(frameRate) ) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Frame Rate : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + self.timing_frame_rate.putData(Float64(frameRate)) + + self.debugPrint('fede4') + + +###Frame Area + try: + x = self.frame_x.data() + y = self.frame_y.data() + width = self.frame_width.data() + height = self.frame_height.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Frame Area value') + raise mdsExceptions.TclFAILED_ESSENTIAL # status = PTGREY.ptgreyLib.getReadoutArea(self.handle, byref(x), byref(y), byref(width), byref(height)) # if status < 0: @@ -397,353 +374,323 @@ def init(self): # Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Readout Area : ' + self.error.raw) # raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setReadoutArea( - self.handle, c_int(x), c_int(y), c_int(width), c_int(height)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Set Frame Area : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setReadoutArea(self.handle, c_int(x), c_int(y), c_int(width), c_int(height)) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Frame Area : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + -# Focal Length +###Focal Length # try: # focalLength = self.cam_setup_focal_length.data() # except: # Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Focal Length value') # raise mdsExceptions.TclFAILED_ESSENTIAL - -# Frame Trigger mode - try: - burstDuration = self.timing_burst_dur.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid acquisition duration value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - triggerMode = self.timing_trig_mode.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid trigger mode value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - trigSource = self.timing_trig_source.data() - except: - if triggerMode == 'EXTERNAL': - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid trigger source value') - raise mdsExceptions.TclFAILED_ESSENTIAL - else: - trigSource = array([0.]) - - self.debugPrint("OK " + triggerMode) - if triggerMode == 'EXTERNAL': # 0=internal 1=external trigger - trigModeCode = c_int(1) + +###Frame Trigger mode + try: + burstDuration = self.timing_burst_dur.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid acquisition duration value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + triggerMode = self.timing_trig_mode.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid trigger mode value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + trigSource = self.timing_trig_source.data() + except: + if triggerMode == 'EXTERNAL': + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid trigger source value') + raise mdsExceptions.TclFAILED_ESSENTIAL else: - trigSource = array([0.]) - trigModeCode = c_int(0) - - numTrigger = trigSource.size - self.debugPrint("Trigger Num.: ", numTrigger) - self.debugPrint("Trigger Source: ", trigSource) - - timeBase = Data.compile(" $ : $ + $ :(zero( size( $ ), 0.) + 1.) * 1./$", - trigSource, trigSource, burstDuration, trigSource, frameRate) + trigSource = array([0.]) + + self.debugPrint("OK " + triggerMode ) + if triggerMode == 'EXTERNAL': #0=internal 1=external trigger + trigModeCode=c_int(1) + else: + trigSource = array([0.]) + trigModeCode=c_int(0) + + numTrigger = trigSource.size + self.debugPrint("Trigger Num.: ", numTrigger) + self.debugPrint("Trigger Source: ", trigSource) + + + timeBase = Data.compile(" $ : $ + $ :(zero( size( $ ), 0.) + 1.) * 1./$", trigSource, trigSource, burstDuration, trigSource, frameRate) + + self.debugPrint("Timebase Data = " + Data.decompile(timeBase)) + + self.timing_time_base.putData(timeBase) + status = PTGREY.ptgreyLib.setTriggerMode(self.handle, trigModeCode, c_double(burstDuration), numTrigger) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Internal/External Trigger : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + +###Streaming + try: + streamingMode = self.streaming_mode.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming mode setup') + raise mdsExceptions.TclFAILED_ESSENTIAL + + + if streamingMode == 'Stream and Store': + streamingEnabled = c_int(1) + storeEnabled = c_int(1) + elif streamingMode == 'Only Stream': + streamingEnabled = c_int(1) + storeEnabled = c_int(0) + else: #streamingMode == 'Only Store': + streamingEnabled = c_int(0) + storeEnabled = c_int(1) + + + if 1: #streamingEnabled (FM: setStreamingMode use this flag) + try: + if self.streaming_autoscale.data() == 'YES' : + autoAdjustLimit = c_int(1) + else: + autoAdjustLimit = c_int(0) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming autoscale parameter value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + lowLim = c_int(self.streaming_lolim.data()) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming low temperature limit parameter value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + highLim = c_int(self.streaming_hilim.data()) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming high temperature limit parameter value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + streamingPort = c_int(self.streaming_port.data()) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming port parameter value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + streamingServer = self.streaming_server.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming server parameter value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + adjRoiX = c_int(self.streaming_adjroix.data()) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming ROI x value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + adjRoiY = c_int(self.streaming_adjroiy.data()) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming ROI y value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + adjRoiW = c_int(self.streaming_adjroiw.data()) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming ROI width value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + try: + adjRoiH = c_int(self.streaming_adjroih.data()) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming ROI height value') + raise mdsExceptions.TclFAILED_ESSENTIAL + + self.debugPrint("lowLim ", lowLim) + self.debugPrint("highLim ", highLim) +# self.debugPrint("frameTempUnitCode ", frameTempUnitCode) + self.debugPrint("streamingPort ", streamingPort) + self.debugPrint("streamingServer ", streamingServer) + self.debugPrint("streaming adj ROI x ", adjRoiX) + self.debugPrint("streaming adj ROI y ", adjRoiY) + self.debugPrint("streaming adj ROI w ", adjRoiW) + self.debugPrint("streaming adj ROI h ", adjRoiH) + #FM: recover device name and pass it to setStreaming to overlay text on frame!!! + deviceName = str(self).rsplit(":",1) + deviceName = deviceName[1] + self.debugPrint("Device Name ", deviceName) - self.debugPrint("Timebase Data = " + Data.decompile(timeBase)) + status = PTGREY.ptgreyLib.setStreamingMode(self.handle, streamingEnabled, autoAdjustLimit, c_char_p(streamingServer), streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, c_char_p(deviceName)); + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute streaming setup mode : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL - self.timing_time_base.putData(timeBase) - status = PTGREY.ptgreyLib.setTriggerMode( - self.handle, trigModeCode, c_double(burstDuration), numTrigger) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Set Internal/External Trigger : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL +###Acquisition -# Streaming - try: - streamingMode = self.streaming_mode.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming mode setup') - raise mdsExceptions.TclFAILED_ESSENTIAL - if streamingMode == 'Stream and Store': - streamingEnabled = c_int(1) - storeEnabled = c_int(1) - elif streamingMode == 'Only Stream': - streamingEnabled = c_int(1) - storeEnabled = c_int(0) - else: # streamingMode == 'Only Store': - streamingEnabled = c_int(0) - storeEnabled = c_int(1) - - if 1: # streamingEnabled (FM: setStreamingMode use this flag) - try: - if self.streaming_autoscale.data() == 'YES': - autoAdjustLimit = c_int(1) - else: - autoAdjustLimit = c_int(0) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming autoscale parameter value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - lowLim = c_int(self.streaming_lolim.data()) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming low temperature limit parameter value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - highLim = c_int(self.streaming_hilim.data()) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming high temperature limit parameter value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - streamingPort = c_int(self.streaming_port.data()) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming port parameter value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - streamingServer = self.streaming_server.data() - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming server parameter value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - adjRoiX = c_int(self.streaming_adjroix.data()) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming ROI x value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - adjRoiY = c_int(self.streaming_adjroiy.data()) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming ROI y value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - adjRoiW = c_int(self.streaming_adjroiw.data()) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming ROI width value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - try: - adjRoiH = c_int(self.streaming_adjroih.data()) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid streaming ROI height value') - raise mdsExceptions.TclFAILED_ESSENTIAL - - self.debugPrint("lowLim ", lowLim) - self.debugPrint("highLim ", highLim) -# self.debugPrint("frameTempUnitCode ", frameTempUnitCode) - self.debugPrint("streamingPort ", streamingPort) - self.debugPrint("streamingServer ", streamingServer) - self.debugPrint("streaming adj ROI x ", adjRoiX) - self.debugPrint("streaming adj ROI y ", adjRoiY) - self.debugPrint("streaming adj ROI w ", adjRoiW) - self.debugPrint("streaming adj ROI h ", adjRoiH) - # FM: recover device name and pass it to setStreaming to overlay text on frame!!! - deviceName = str(self).rsplit(":", 1) - deviceName = deviceName[1] - self.debugPrint("Device Name ", deviceName) - - status = PTGREY.ptgreyLib.setStreamingMode(self.handle, streamingEnabled, autoAdjustLimit, c_char_p( - streamingServer), streamingPort, lowLim, highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, c_char_p(deviceName)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot execute streaming setup mode : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL + try: + acqSkipFrameNumber = c_int( self.timing_skip_frame.data() ) + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid acquisition decimation value') + raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setAcquisitionMode(self.handle, storeEnabled , acqSkipFrameNumber) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute acquisition setup mode : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL -# Acquisition + try: + treePtr = c_void_p(0) + status = PTGREY.mdsLib.camOpenTree(c_char_p(self.getTree().name), c_int(self.getTree().shot), byref(treePtr)) + if status == -1: + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot open tree') + raise mdsExceptions.TclFAILED_ESSENTIAL + except: + traceback.print_exc() - try: - acqSkipFrameNumber = c_int(self.timing_skip_frame.data()) - except: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Invalid acquisition decimation value') - raise mdsExceptions.TclFAILED_ESSENTIAL + framesNid = self.frames.nid + timebaseNid = self.timing_time_base.nid + framesMetadNid = self.frames_metad.nid + frame0TimeNid = self.frame0_time.nid - status = PTGREY.ptgreyLib.setAcquisitionMode( - self.handle, storeEnabled, acqSkipFrameNumber) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot execute acquisition setup mode : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setTreeInfo( self.handle, treePtr, framesNid, timebaseNid, framesMetadNid, frame0TimeNid) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute set tree info : '+self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL - try: - treePtr = c_void_p(0) - status = PTGREY.mdsLib.camOpenTree( - c_char_p(self.getTree().name), c_int(self.getTree().shot), byref(treePtr)) - if status == -1: - Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot open tree') - raise mdsExceptions.TclFAILED_ESSENTIAL - except: - traceback.print_exc() + self.debugPrint('Init action completed.') + return 1 - framesNid = self.frames.nid - timebaseNid = self.timing_time_base.nid - framesMetadNid = self.frames_metad.nid - frame0TimeNid = self.frame0_time.nid - status = PTGREY.ptgreyLib.setTreeInfo( - self.handle, treePtr, framesNid, timebaseNid, framesMetadNid, frame0TimeNid) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot execute set tree info : '+self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - self.debugPrint('Init action completed.') - return 1 -# CHANGE GAIN +####################CHANGE GAIN def changeGain(self): - # 0:error 1:camera opened 2:camera was already opened - restoreRes = self.restoreInfo() - if restoreRes == 0: - raise mdsExceptions.TclFAILED_ESSENTIAL + restoreRes=self.restoreInfo() #0:error 1:camera opened 2:camera was already opened + if restoreRes == 0: + raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setGain( - self.handle, c_float(self.cam_setup_gain.data())) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot change Gain value : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setGain(self.handle, c_float(self.cam_setup_gain.data())) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot change Gain value : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL - if restoreRes == 1: # camera must be closed because has been opened only for this action - self.removeInfo() + if restoreRes == 1: #camera must be closed because has been opened only for this action + self.removeInfo() - return 1 + return 1 -# CHANGE EXPOSURE +####################CHANGE EXPOSURE def changeExposure(self): - # 0:error 1:camera opened 2:camera was already opened - restoreRes = self.restoreInfo() - if restoreRes == 0: - raise mdsExceptions.TclFAILED_ESSENTIAL + restoreRes=self.restoreInfo() #0:error 1:camera opened 2:camera was already opened + if restoreRes == 0: + raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.setExposure( - self.handle, c_float(self.cam_setup_exposure.data())) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot change Exposure value : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.setExposure(self.handle, c_float(self.cam_setup_exposure.data())) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot change Exposure value : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL - if restoreRes == 1: # camera must be closed because has been opened only for this action - self.removeInfo() + if restoreRes == 1: #camera must be closed because has been opened only for this action + self.removeInfo() - return 1 + return 1 -# READ INTERNAL TEMPERATURE +####################READ INTERNAL TEMPERATURE def readTemperature(self): - # 0:error 1:camera opened 2:camera was already opened - restoreRes = self.restoreInfo() - if restoreRes == 0: - raise mdsExceptions.TclFAILED_ESSENTIAL + restoreRes=self.restoreInfo() #0:error 1:camera opened 2:camera was already opened + if restoreRes == 0: + raise mdsExceptions.TclFAILED_ESSENTIAL - status = PTGREY.ptgreyLib.readInternalTemperature(self.handle) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Read Internal Temperature : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL + status = PTGREY.ptgreyLib.readInternalTemperature(self.handle) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Read Internal Temperature : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL - if restoreRes == 1: # camera must be closed because has been opened only for this action - self.removeInfo() + if restoreRes == 1: #camera must be closed because has been opened only for this action + self.removeInfo() + + return 1 - return 1 ##########start acquisition############################################################################ def startAcquisition(self): - if self.checkWorker(): # FM 20191114 - self.debugPrint( - 'Acquisition already in progress. Action not performed.') - return 1 - - if self.checkInfo(): # FM 20191114 - self.restoreInfo() - else: - Data.execute('DevLogErr($1,$2)', self.nid, - 'Init action must be performed before acquisition : '+self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - - self.debugPrint("Starting acquisition") - self.worker = self.AsynchStore() - self.worker.daemon = True - self.worker.stopReq = False - width = c_int(0) - height = c_int(0) - payloadSize = c_int(0) - status = PTGREY.ptgreyLib.startAcquisition( - self.handle, byref(width), byref(height), byref(payloadSize)) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Start Camera Acquisition : '+self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - self.debugPrint("Acquisition started") - self.worker.configure(self.copy()) - self.saveWorker() - self.worker.start() - return 1 + if self.checkWorker(): #FM 20191114 + self.debugPrint('Acquisition already in progress. Action not performed.') + return 1 + + if self.checkInfo(): #FM 20191114 + self.restoreInfo() + else: + Data.execute('DevLogErr($1,$2)', self.nid, 'Init action must be performed before acquisition : '+self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + self.debugPrint("Starting acquisition") + self.worker = self.AsynchStore() + self.worker.daemon = True + self.worker.stopReq = False + width = c_int(0) + height = c_int(0) + payloadSize = c_int(0) + status = PTGREY.ptgreyLib.startAcquisition(self.handle, byref(width), byref(height), byref(payloadSize)) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Start Camera Acquisition : '+self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + self.debugPrint("Acquisition started") + self.worker.configure(self.copy()) + self.saveWorker() + self.worker.start() + return 1 ##########stop acquisition############################################################################ def stopAcquisition(self): - if self.checkWorker(): # FM 20191114 - self.restoreWorker() - self.worker.stop() - self.removeWorker() - else: - self.debugPrint( - "Camera is not in acquisition. Action not performed.") - return 1 + if self.checkWorker(): #FM 20191114 + self.restoreWorker() + self.worker.stop() + self.worker.join() #CT 20200917 + self.removeWorker() + else: + self.debugPrint("Camera is not in acquisition. Action not performed.") + return 1 ##########software trigger (start saving in mdsplus)############################################ def swTrigger(self): - if not self.checkWorker(): # FM 20191114 - self.debugPrint('Camera not in acquisition. Action not performed.') - return 1 - if not self.checkInfo(): # FM 20191114 - self.debugPrint('Camera not opened. Action not performed.') - return 1 - if self.restoreInfo() == 0: - raise mdsExceptions.TclFAILED_ESSENTIAL - - self.debugPrint('SOFTWARE TRIGGER') - - status = PTGREY.ptgreyLib.softwareTrigger(self.handle) - if status < 0: - PTGREY.ptgreyLib.getLastError(self.handle, self.error) - Data.execute('DevLogErr($1,$2)', self.nid, - 'Cannot Execute Software Trigger : ' + self.error.raw) - raise mdsExceptions.TclFAILED_ESSENTIAL - - return 1 + if not self.checkWorker(): #FM 20191114 + self.debugPrint('Camera not in acquisition. Action not performed.') + return 1 + if not self.checkInfo(): #FM 20191114 + self.debugPrint('Camera not opened. Action not performed.') + return 1 + if self.restoreInfo() == 0: + raise mdsExceptions.TclFAILED_ESSENTIAL + + self.debugPrint('SOFTWARE TRIGGER') + + status = PTGREY.ptgreyLib.softwareTrigger(self.handle) + if status < 0: + PTGREY.ptgreyLib.getLastError(self.handle, self.error) + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Execute Software Trigger : ' + self.error.raw) + raise mdsExceptions.TclFAILED_ESSENTIAL + + return 1 diff --git a/pydevices/RfxDevices/PV2MDSEVENT.py b/pydevices/RfxDevices/PV2MDSEVENT.py new file mode 100644 index 0000000000..abd3032566 --- /dev/null +++ b/pydevices/RfxDevices/PV2MDSEVENT.py @@ -0,0 +1,235 @@ +from MDSplus import Device, Data, Int32 +from ctypes import CDLL,c_char_p,c_short,byref, c_int +from MDSplus.mdsExceptions import DevBAD_PARAMETER + +class PV2MDSEVENT(Device): + """MDS event generation on process variable value threshold """ + parts = [ + {'path':':COMMENT','type':'text'}, + {'path':':SHOT_TIME','type':'text'}, + ] + for i in range(1,7): + parts.extend([ + {'path':'.EV_%d'%(i),'type':'structure'}, + {'path':'.EV_%d:WAVE_REF'%(i),'type':'signal'}, + {'path':'.EV_%d:PV_NAME'%(i),'type':'numeric', 'value':0}, + {'path':'.EV_%d:MODE'%(i),'type':'text', 'value':'RIDING'}, + {'path':'.EV_%d:THRESHOLD'%(i),'type':'numeric', 'value':0}, + {'path':'.EV_%d:DELAY'%(i),'type':'numeric', 'value':0}, + {'path':'.EV_%d:PV_TIME'%(i),'type':'numeric', 'value':0}, + {'path':'.EV_%d:TRIG_TIME'%(i),'type':'numeric', 'value':0}, + + + + + {'path':'.EV_%d:POST_SMP'%(i),'type':'numeric', 'value':10000}, + {'path':'.EV_%d:CONT_FREQ'%(i),'type':'numeric', 'value':10000}, + {'path':'.EV_%d:FAST_FREQ'%(i),'type':'numeric', 'value':10000}, + {'path':'.EV_%d:SLOW_FREQ'%(i),'type':'numeric', 'value':10000}, + {'path':'.EV_%d:SLOW_EV'%(i),'type':'text'}, + {'path':'.EV_%d:FAST_EV'%(i),'type':'text'}, + {'path':'.EV_%d:CONT_EV'%(i),'type':'text'}, + {'path':'.EV_%d:SLOW_TRIG'%(i),'type':'numeric'}, + {'path':'.EV_%d:FAST_TRIG'%(i),'type':'numeric'}, + {'path':'.EV_%d:CONT_TRIG'%(i),'type':'numeric'}, + {'path':'.EV_%d:FREQ'%(i),'type':'numeric'}, + {'path':'.EV_%d:EV'%(i),'type':'text'}, + {'path':'.EV_%d:TRIG'%(i),'type':'numeric'} + ]) + parts.extend([ + {'path':':START_ACTION','type':'action', + 'valueExpr':"Action(Dispatch('SERVER','INIT',50,None),Method(None,'init',head))", + 'options':('no_write_shot',)} + ]) + del(i) + + + modeDict = {'CONTINUOUS':'STREAMING', 'SLOW':'TRIGGER_STREAMING', 'FAST':'TRIGGER_STREAMING'} + + def init(self): + + error = False + for board in range(1,7): + + try: + devPath = self.__getattr__('conf_%d_dev_path'%(board)).getData() + except Exception as ex: + emsg = 'Missing device Path for board %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + mode = self.__getattr__('conf_%d_mode'%(board)).data() + except: + emsg = 'Missing device acquisition mode for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + self.getTree().getNode(devPath.getPath()+':MODE').putData(self.modeDict[mode]); + except Exception as ex: + emsg = 'Error on setting acquisition mode for conf %d : %s'%(board, str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + + if mode == 'CONTINUOUS' : + + try: + freq = self.__getattr__('conf_%d_cont_freq'%(board)).getData() + self.__getattr__('conf_%d_freq'%(board)).putData(freq) + except: + emsg = 'Error on updating continuous frequency for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + mdsEvent = self.__getattr__('conf_%d_cont_ev'%(board)).getData() + self.__getattr__('conf_%d_ev'%(board)).putData(mdsEvent) + self.getTree().getNode(devPath.getPath()+':MDS_TRIG_EV').putData(mdsEvent); + except Exception as ex: + emsg = 'Error on updating continuous mds event for conf %d : %s'%(board,str(ex)) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + trig = self.__getattr__('conf_%d_cont_trig'%(board)).getData() + self.__getattr__('conf_%d_trig'%(board)).putData(trig) + except: + emsg = 'Error on updating continuous trigger for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + + elif mode == 'SLOW' : + + try: + freq = self.__getattr__('conf_%d_slow_freq'%(board)).getData() + self.__getattr__('conf_%d_freq'%(board)).putData(freq) + except: + emsg = 'Error on updating continuous frequency for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + mdsEvent = self.__getattr__('conf_%d_slow_ev'%(board)).getData() + self.__getattr__('conf_%d_ev'%(board)).putData(mdsEvent) + self.getTree().getNode(devPath.getPath()+':MDS_TRIG_EV').putData(mdsEvent); + except: + emsg = 'Error on updating continuous mds event for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + trig = self.__getattr__('conf_%d_slow_trig'%(board)).getData() + self.__getattr__('conf_%d_trig'%(board)).putData(trig) + except: + emsg = 'Error on updating continuous trigger for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + preSmp = int( abs(startTime) * freq ); + self.__getattr__('conf_%d_pre_smp'%(board)).putData(Int32(preSmp)) + except: + emsg = 'Error on updating pre samples value for conf %d in slow acquisition mode'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + postSmp = int( abs(stopTime) * freq ); + self.__getattr__('conf_%d_pre_smp'%(board)).putData(Int32(postSmp)) + except: + emsg = 'Error on updating post samples value for conf %d in slow acquisition mode'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + + elif mode == 'FAST' : + + try: + freq = self.__getattr__('conf_%d_fast_freq'%(board)).getData() + self.__getattr__('conf_%d_freq'%(board)).putData(freq) + except: + emsg = 'Error on updating continuous frequency for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + mdsEvent = self.__getattr__('conf_%d_fast_ev'%(board)).getData() + self.__getattr__('conf_%d_ev'%(board)).putData(mdsEvent) + self.getTree().getNode(devPath.getPath()+':MDS_TRIG_EV').putData(mdsEvent); + except: + emsg = 'Error on updating continuous mds event for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + trig = self.__getattr__('conf_%d_fast_trig'%(board)).getData() + self.__getattr__('conf_%d_trig'%(board)).putData(trig) + except: + emsg = 'Error on updating continuous trigger for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + else: + emsg = 'Invalid acquisition mode %s for conf %d'%(mode, board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + + if mode == 'SLOW' or mode == 'FAST' : + + try: + startTime = self.__getattr__('conf_%d_start_time'%(board)).data() + except: + emsg = 'Missing start time value for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + stopTime = self.__getattr__('conf_%d_stop_time'%(board)).data() + except: + emsg = 'Missing stop time value for conf %d'%(board) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + preSmp = int( abs(startTime) * freq ); + self.__getattr__('conf_%d_pre_smp'%(board)).putData(Int32(preSmp)) + except: + emsg = 'Error on updating pre samples value for conf %d in %s acquisition mode'%(board, mode) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + try: + postSmp = int( abs(stopTime) * freq ); + self.__getattr__('conf_%d_post_smp'%(board)).putData(Int32(postSmp)) + except: + emsg = 'Error on updating post samples value for conf %d in %s acquisition mode'%(board, mode) + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + error = True + continue + + if error : + raise DevBAD_PARAMETER + + return 1 diff --git a/pydevices/RfxDevices/RGA.py b/pydevices/RfxDevices/RGA.py new file mode 100755 index 0000000000..9357aa5cc6 --- /dev/null +++ b/pydevices/RfxDevices/RGA.py @@ -0,0 +1,60 @@ +from MDSplus import Device, Data, Range, Dimension, Window, Signal, Int16Array +from ctypes import CDLL,c_char_p,c_short,byref, c_int +import socket + +class RGA(Device): + """Residual Gas Analizer""" + parts = [ + {'path':':COMMENT','type':'text'}, + {'path':':FILE','type':'text'}, + {'path':':SERVER_ADDR','type':'text'}, + {'path':':SERVER_PORT','type':'numeric'}, + {'path':':PRESSURE','type':'signal', 'options':('no_write_model','compress_on_put')} + ] + for i in range(101): + parts.extend([ + {'path':'.MASS_%03d'%(i),'type':'structure'}, + {'path':'.MASS_%03d:DESCRIPTON'%(i),'type':'text'}, + {'path':'.MASS_%03d:DATA'%(i),'type':'signal', 'options':('no_write_model','compress_on_put')} + ]) + parts.extend([ + {'path':':START_ACTION','type':'action', + 'valueExpr':"Action(Dispatch('SERVER','INIT',50,None),Method(None,'start_store',head))", + 'options':('no_write_shot',)}, + {'path':':STOP_ACTION','type':'action', + 'valueExpr':"Action(Dispatch('SERVER','STORE',50,None),Method(None,'stop_store',head))", + 'options':('no_write_shot',)}, + ]) + del(i) + + def sendMessage(self, msg): + + print('Send message ', msg) + try: + serverAddr = self.server_addr.data(); + except: + emsg = 'Missing server address' + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + raise DevBAD_PARAMETER + + try: + serverPort = self.server_port.data(); + except: + emsg = 'Missing server port' + Data.execute('DevLogErr($1,$2)', self.getNid(), emsg ) + raise DevBAD_PARAMETER + + # Create a datagram socket + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); + + s.sendto(msg, (serverAddr, serverPort)) + + + def start_store(self): + msg = 'START GVS %d'%(self.getTree().shot) + self.sendMessage(msg) + + def stop_store(self): + msg = 'STOP GVS %d'%(self.getTree().shot) + self.sendMessage(msg) + diff --git a/pydevices/RfxDevices/SPIDER_FFT.py b/pydevices/RfxDevices/SPIDER_FFT.py index 8e43cc17bd..ad3c71ece9 100644 --- a/pydevices/RfxDevices/SPIDER_FFT.py +++ b/pydevices/RfxDevices/SPIDER_FFT.py @@ -101,6 +101,7 @@ def store(self): outCount = 0 outSegCount = 0 for segIdx in range(nSegments): + print('Doing Segment '+str(segIdx) +' of ' + str(nSegments)) segData = inNode.getSegment(segIdx).data() segData = segData * inRange*inGain/8192. + inOffset numBursts = int(round(len(segData)/burstSize)) @@ -112,7 +113,7 @@ def store(self): outAmplSegs.append([]) outPhaseSegs.append([]) for burstIdx in range(numBursts): - fftData = np.fft.fft(segData[burstIdx*burstSize:(burstIdx+1)*burstSize]) + fftData = np.fft.fft(segData[int(burstIdx*burstSize):int((burstIdx+1)*burstSize)]) fftAmp = np.abs(fftData) fftAmp = fftAmp[:len(fftAmp)/2] #keep only significant part fftPhs = np.angle(fftData) @@ -128,8 +129,8 @@ def store(self): outFreqSegs[hIdx].append(acqFreq * float(maxIdx + origOffset) / burstSize) outAmplSegs[hIdx].append(fftAmp[maxIdx]) outPhaseSegs[hIdx].append(fftPhs[maxIdx]) - np.delete(fftAmp, maxIdx) - np.delete(fftPhs, maxIdx) + fftAmp = np.delete(fftAmp, maxIdx) + fftPhs = np.delete(fftPhs, maxIdx) outCount = outCount + 1 if outCount > SPIDER_FFT.OUT_SEGMENT_SIZE: startTime = Float64(trigTime + outSegCount * SPIDER_FFT.OUT_SEGMENT_SIZE / trigFreq) diff --git a/pydevices/RfxDevices/SPIDER_SETUP.py b/pydevices/RfxDevices/SPIDER_SETUP.py index 997a9f1bbb..48051de63e 100644 --- a/pydevices/RfxDevices/SPIDER_SETUP.py +++ b/pydevices/RfxDevices/SPIDER_SETUP.py @@ -44,15 +44,15 @@ class SPIDER_SETUP(Device): for i in range(0,8): parts.append({'path':'.ISEPS.WAVE_%d'%(i+1), 'type':'structure'}) parts.append({'path':'.ISEPS.WAVE_%d:WAVE'%(i+1), 'type':'signal'}) - parts.append({'path':'.ISEPS.WAVE_%d:MIN_X'%(i+1), 'type':'numeric'}) - parts.append({'path':'.ISEPS.WAVE_%d:MAX_X'%(i+1), 'type':'numeric'}) + parts.append({'path':'.ISEPS.WAVE_%d:MIN_X'%(i+1), 'type':'numeric', 'valueExpr': 'Data.compile("$1", head.spider_wref_start)'}) + parts.append({'path':'.ISEPS.WAVE_%d:MAX_X'%(i+1), 'type':'numeric', 'valueExpr': 'Data.compile("$1", head.spider_wref_stop)'}) parts.append({'path':'.ISEPS.WAVE_%d:MIN_Y'%(i+1), 'type':'numeric'}) parts.append({'path':'.ISEPS.WAVE_%d:MAX_Y'%(i+1), 'type':'numeric'}) parts.append({'path':'.ISEPS.WAVE_REC', 'type':'structure'}) parts.append({'path':'.ISEPS.WAVE_REC:WAVE', 'type':'signal'}) - parts.append({'path':'.ISEPS.WAVE_REC:MIN_X', 'type':'numeric'}) - parts.append({'path':'.ISEPS.WAVE_REC:MAX_X', 'type':'numeric'}) + parts.append({'path':'.ISEPS.WAVE_REC:MIN_X', 'type':'numeric', 'value': 0}) + parts.append({'path':'.ISEPS.WAVE_REC:MAX_X', 'type':'numeric', 'value': 1}) parts.append({'path':'.ISEPS.WAVE_REC:MIN_Y', 'type':'numeric'}) parts.append({'path':'.ISEPS.WAVE_REC:MAX_Y', 'type':'numeric'}) @@ -63,8 +63,8 @@ class SPIDER_SETUP(Device): for i in range(0,8): parts.append({'path':'.GVS.WAVE_%d'%(i+1), 'type':'structure'}) parts.append({'path':'.GVS.WAVE_%d:WAVE'%(i+1), 'type':'signal'}) - parts.append({'path':'.GVS.WAVE_%d:MIN_X'%(i+1), 'type':'numeric'}) - parts.append({'path':'.GVS.WAVE_%d:MAX_X'%(i+1), 'type':'numeric'}) + parts.append({'path':'.GVS.WAVE_%d:MIN_X'%(i+1), 'type':'numeric', 'valueExpr': 'Data.compile("$1", head.spider_wref_start)'}) + parts.append({'path':'.GVS.WAVE_%d:MAX_X'%(i+1), 'type':'numeric', 'valueExpr': 'Data.compile("$1", head.spider_wref_stop)'}) parts.append({'path':'.GVS.WAVE_%d:MIN_Y'%(i+1), 'type':'numeric'}) parts.append({'path':'.GVS.WAVE_%d:MAX_Y'%(i+1), 'type':'numeric'}) @@ -116,15 +116,15 @@ class SPIDER_SETUP(Device): for i in range(0,8): parts.append({'path':'.AGPS.WAVE_%d'%(i+1), 'type':'structure'}) parts.append({'path':'.AGPS.WAVE_%d:WAVE'%(i+1), 'type':'signal'}) - parts.append({'path':'.AGPS.WAVE_%d:MIN_X'%(i+1), 'type':'numeric'}) - parts.append({'path':'.AGPS.WAVE_%d:MAX_X'%(i+1), 'type':'numeric'}) + parts.append({'path':'.AGPS.WAVE_%d:MIN_X'%(i+1), 'type':'numeric', 'valueExpr': 'Data.compile("$1", head.spider_wref_start)'}) + parts.append({'path':'.AGPS.WAVE_%d:MAX_X'%(i+1), 'type':'numeric', 'valueExpr': 'Data.compile("$1", head.spider_wref_stop)'}) parts.append({'path':'.AGPS.WAVE_%d:MIN_Y'%(i+1), 'type':'numeric'}) parts.append({'path':'.AGPS.WAVE_%d:MAX_Y'%(i+1), 'type':'numeric'}) parts.append({'path':'.AGPS.WAVE_REC', 'type':'structure'}) parts.append({'path':'.AGPS.WAVE_REC:WAVE', 'type':'signal'}) - parts.append({'path':'.AGPS.WAVE_REC:MIN_X', 'type':'numeric'}) - parts.append({'path':'.AGPS.WAVE_REC:MAX_X', 'type':'numeric'}) + parts.append({'path':'.AGPS.WAVE_REC:MIN_X', 'type':'numeric', 'value': 0}) + parts.append({'path':'.AGPS.WAVE_REC:MAX_X', 'type':'numeric', 'value': 1}) parts.append({'path':'.AGPS.WAVE_REC:MIN_Y', 'type':'numeric'}) parts.append({'path':'.AGPS.WAVE_REC:MAX_Y', 'type':'numeric'}) @@ -137,8 +137,8 @@ class SPIDER_SETUP(Device): for i in range(8,20): parts.append({'path':'.ISEPS.WAVE_%d'%(i+1), 'type':'structure'}) parts.append({'path':'.ISEPS.WAVE_%d:WAVE'%(i+1), 'type':'signal'}) - parts.append({'path':'.ISEPS.WAVE_%d:MIN_X'%(i+1), 'type':'numeric'}) - parts.append({'path':'.ISEPS.WAVE_%d:MAX_X'%(i+1), 'type':'numeric'}) + parts.append({'path':'.ISEPS.WAVE_%d:MIN_X'%(i+1), 'type':'numeric', 'valueExpr': 'Data.compile("$1", head.spider_wref_start)'}) + parts.append({'path':'.ISEPS.WAVE_%d:MAX_X'%(i+1), 'type':'numeric', 'valueExpr': 'Data.compile("$1", head.spider_wref_stop)'}) parts.append({'path':'.ISEPS.WAVE_%d:MIN_Y'%(i+1), 'type':'numeric'}) parts.append({'path':'.ISEPS.WAVE_%d:MAX_Y'%(i+1), 'type':'numeric'}) parts.append({'path':'.ISEPS.WAVE_%d:LABEL'%(i+1), 'type':'text', 'value':'ISESP wave %d'%(i+1)}) @@ -161,7 +161,56 @@ class SPIDER_SETUP(Device): parts.append({'path':'.ISEPS:CS1_I_REF' , 'type':'numeric', 'value':0}) parts.append({'path':'.ISEPS:CS2_I_REF' , 'type':'numeric', 'value':0}) - +# Add SAFETY parameters. session and nominal limits in Plasma and Vaccum Pulses + + parts.append({'path':'.SAFETY_PAR', 'type':'structure'}) + parts.append({'path':'.SAFETY_PAR.PLASMA', 'type':'structure'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:AGPS_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:GVS_PRESMIN', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:GVS_PRESMAX', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISEG_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISRF_TE_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISSS_CLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISPG_CLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISRF1_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISRF2_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISRF3_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISRF4_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISBI_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISBP_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISBI_CLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.PLASMA:ISBP_CLIM', 'type':'Numeric'}) + + parts.append({'path':'.SAFETY_PAR.VACUUM', 'type':'structure'}) + parts.append({'path':'.SAFETY_PAR.VACUUM:AGPS_VMAX', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.VACUUM:ISRF1_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.VACUUM:ISRF2_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.VACUUM:ISRF3_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.VACUUM:ISRF4_PLIM', 'type':'Numeric'}) + + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA', 'type':'structure'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:AGPS_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:GVS_PRESMIN', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:GVS_PRESMAX', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISEG_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISRF_TE_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISSS_CLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISPG_CLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISRF1_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISRF2_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISRF3_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISRF4_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISBI_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISBP_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISBI_CLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_PLASMA:ISBP_CLIM', 'type':'Numeric'}) + + parts.append({'path':'.SAFETY_PAR.NOM_VACUUM', 'type':'structure'}) + parts.append({'path':'.SAFETY_PAR.NOM_VACUUM:AGPS_VLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_VACUUM:ISRF1_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_VACUUM:ISRF2_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_VACUUM:ISRF3_PLIM', 'type':'Numeric'}) + parts.append({'path':'.SAFETY_PAR.NOM_VACUUM:ISRF4_PLIM', 'type':'Numeric'}) del(i) diff --git a/pydevices/RfxDevices/STK_TEMP.py b/pydevices/RfxDevices/STK_TEMP.py new file mode 100644 index 0000000000..715788385a --- /dev/null +++ b/pydevices/RfxDevices/STK_TEMP.py @@ -0,0 +1,187 @@ +from MDSplus import mdsExceptions, Device, Data, version, Int64, Float32 +#from ctypes import CDLL, byref, c_double, c_int, c_void_p, c_char_p, create_string_buffer +#from numpy import array +from threading import Thread +#import traceback +try: + import serial +except: + pass +from datetime import datetime + +class STK_TEMP(Device): + """STK_TEMP Device""" + parts=[ #offset nid + {'path':':PORT_NAME', 'type':'text', 'value':'/dev/ttyS0'}, #1 + {'path':':COMMENT', 'type':'text'}, + {'path':':TEMPERATURE', 'type':'signal','options':('no_write_model', 'no_compress_on_put')} + ] + + parts.append({'path':':INIT_ACT','type':'action', + 'valueExpr':"Action(Dispatch('STRIKE_SERVER','PULSE_PREPARATION',50,None),Method(None,'init',head))", + 'options':('no_write_shot',)}) + parts.append({'path':':START_ACT','type':'action', + 'valueExpr':"Action(Dispatch('STRIKE_SERVER','INIT',50,None),Method(None,'startAcquisition',head))", + 'options':('no_write_shot',)}) + parts.append({'path':':STOP_ACT','type':'action', + 'valueExpr':"Action(Dispatch('STRIKE_SERVER','STORE',50,None),Method(None,'stopAcquisition',head))", + 'options':('no_write_shot',)}) + + handle = -1 + handles = {} + workers = {} + + def debugPrint(self, msg="", obj=""): + print( "------ DEBUG " + self.name + ":" + msg, obj ); + + + """Asynchronous readout internal class""" + class AsynchStore(Thread): + + def configure(self, device): + self.device = device + self.frameIdx = 0 + self.stopReq = False + + def run(self): + + self.device.debugPrint("Asychronous acquisition thread") + + self.device.handle.reset_input_buffer() + idx=0 + epoch=datetime(1970,1,1) + temperatureNid = self.device.temperature + + while not self.stopReq: + if self.device.handle.in_waiting>0: + temperature=float(self.device.handle.readline().decode('utf-8').rstrip()) + idx+=1 + if idx==1: + timestamp0=datetime.utcnow() + deltaT=0.0 + dt=timestamp0-epoch + int64Time=dt.microseconds/1000+dt.seconds*1000+dt.days*86400000 + else: + timestamp=datetime.utcnow() + dt=timestamp-timestamp0 + deltaT=dt.microseconds/1000000.0+dt.seconds+dt.days*86400 + dt=timestamp-epoch + int64Time=dt.microseconds/1000+dt.seconds*1000+dt.days*86400000 + print (deltaT, temperature) + + temperatureNid.putRow(1, Float32(temperature), Int64(int64Time)) + + self.device.debugPrint("End acquisition thread") + self.device.removeInfo() + + def stop(self): + self.device.debugPrint("STOP acquisition loop") + self.stopReq = True + + + def saveWorker(self): + STK_TEMP.workers[self.nid] = self.worker + +###save Info### +#saveInfo and restoreInfo allow to manage multiple occurrences of camera devices +#and to avoid opening and closing devices handles + def saveInfo(self): + STK_TEMP.handles[self.nid] = self.handle + +###restore worker### + def restoreWorker(self): + if self.nid in STK_TEMP.workers.keys(): + self.worker = STK_TEMP.workers[self.nid] + return 1 + else: + Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot restore worker!!') + raise mdsExceptions.TclFAILED_ESSENTIAL + return 1 + +###restore info### + def restoreInfo(self): + self.debugPrint("restore Info") + + if self.nid in STK_TEMP.handles.keys(): + self.handle = STK_TEMP.handles[self.nid] + self.debugPrint('RESTORE INFO HANDLE TROVATO', self.handle) + else: + self.debugPrint('RESTORE INFO HANDLE NON TROVATO') + try: + name = self.port_name.data() + except: + Data.execute('DevLogErr($1,$2)', self.nid, 'Missing device name' ) + raise mdsExceptions.TclFAILED_ESSENTIAL + try: + self.handle = serial.Serial(name, 9600, timeout=0.5) + self.debugPrint("Serial Port opened: ", self.handle) + except: + self.debugPrint('ERROR opening serial port...') + raise mdsExceptions.TclFAILED_ESSENTIAL + + return 1 + +###remove info### + def removeInfo(self): + try: + self.handle.close() + self.debugPrint('Serial Port closed...') + except: + self.debugPrint('ERROR TRYING TO CLOSE SERIAL PORT') + + try: + del(STK_TEMP.handles[self.nid]) + except: + self.debugPrint('ERROR TRYING TO REMOVE INFO') + + +##########init############################################################################ + def init(self): + if self.restoreInfo() == 0: + raise mdsExceptions.TclFAILED_ESSENTIAL + + self.saveInfo() + #### serial port opened on restoreInfo() + + self.debugPrint('Init action completed.') + return 1 + + + +##########start acquisition############################################################################ + def startAcquisition(self): + if self.restoreInfo() == 0: + raise mdsExceptions.TclFAILED_ESSENTIAL + + #Module in acquisition check + try: + self.restoreWorker() + if ( self.worker != None and self.worker.isAlive() ): + self.debugPrint("Stop acquisition Thread...") + self.stopAcquisition() + self.debugPrint("Initialize...") + self.init() + self.restoreInfo() + except: + pass + + self.debugPrint("Starting Acquisition...") + + self.worker = self.AsynchStore() + self.worker.daemon = True + self.worker.stopReq = False + + + self.debugPrint("OK!") + self.worker.configure(self) + self.saveWorker() + self.worker.start() + return 1 + + +##########stop acquisition############################################################################ + def stopAcquisition(self): + if self.restoreWorker() : + self.worker.stop() + return 1 + diff --git a/tdi/RfxDevices/DIO4HWInit.fun b/tdi/RfxDevices/DIO4HWInit.fun index 3ad420b9bb..7019412cfe 100644 --- a/tdi/RfxDevices/DIO4HWInit.fun +++ b/tdi/RfxDevices/DIO4HWInit.fun @@ -1,8 +1,7 @@ public fun DIO4HWInit(in _nid, in _board_id, in _ext_clock, in _rec_event, in _synch_event) { - private _DIO4_CLOCK_SOURCE_TIMING_HIGHWAY = 0x3; - private _DIO4_CLOCK_SOURCE_INTERNAL = 0x0; + private _DIO4_CLOCK_SOURCE_INTERNAL = 0x0; private _DIO4_CLOCK_SOURCE_IO = 0x1; private _DIO4_TH_ASYNCHRONOUS = 0; private _DIO4_TH_SYNCHRONOUS = 1; @@ -26,6 +25,12 @@ public fun DIO4HWInit(in _nid, in _board_id, in _ext_clock, in _rec_event, in _s private _DIO4_CLOCK_SOURCE_OK = 0x1; private _DIO4_CLOCK_SOURCE_NOK = 0x0; + + private _CLOCK_SOURCE_INTERNAL = 0; + private _CLOCK_SOURCE_HIGHWAY = 1; + private _CLOCK_SOURCE_EXTERNAL = 2; + + /* private _NO_EVENT = -1; */ /* if( size( _synch_event ) == 1 && _synch_event[0] == _NO_EVENT ) _synch_event = []; */ @@ -75,19 +80,62 @@ public fun DIO4HWInit(in _nid, in _board_id, in _ext_clock, in _rec_event, in _s return(0); } +/******************************************************************************/ +/* +** The external clock is routed via the PLL to synchronize +** the timing channel clock to this external clock. +** The timing channel will count with steps of 100ns. +** +** This is not a normal feature and has to be 'hacked' +** in the following way. Configuring the PLL registers is +** also needed later on. Because of this synchronizing to an +** external clock is only discribed in application note. +** RESET clk2pll feature if it was set on a previous initialization +*/ + + _dwTemp = long(0); + _status = DIO4->DIO4_Tst_ReadRegister(val(_handle), val(long(0x008)), ref(_dwTemp)); + if(_status != 0) + { + if(_nid != 0) + DevLogErr(_nid, "Error reading register in DIO4 device, board ID = "// _board_id); + else + write(*, "Error reading register in DIO4 device, board ID = "// _board_id); + return(0); + } + +write(*,' Reg 0x008 ', _dwTemp); +_dwTemp = _dwTemp & ~long(0x800); /* Disable 'hidden' clk2pll feature */ +write(*, ' Reg 0x008 ', _dwTemp); + + _status = DIO4->DIO4_Tst_WriteRegister(val(_handle), val(long(0x008)), val(long(_dwTemp))); + if(_status != 0) + { + if(_nid != 0) + DevLogErr(_nid, "Error writing register in DIO4 device, board ID = "// _board_id); + else + write(*, "Error writing register in DIO4 device, board ID = "// _board_id); + return(0); + } +/******************************************************************************/ + /* Set clock functions */ - - _clock_source = byte(_DIO4_CLOCK_SOURCE_INTERNAL); + if( _ext_clock == _CLOCK_SOURCE_INTERNAL || _ext_clock == _CLOCK_SOURCE_EXTERNAL ) + { + write(*, 'Clock source INTERNAL'); + _clock_source = byte(_DIO4_CLOCK_SOURCE_INTERNAL); /* - _out = byte(_DIO4_TH_OUTPUT_DISABLE); TT + _out = byte(_DIO4_TH_OUTPUT_DISABLE); TT */ - _out = byte(_DIO4_TH_OUTPUT_ENABLE); + _out = byte(_DIO4_TH_OUTPUT_ENABLE); + } + - if(_ext_clock == 1) + if( _ext_clock == _CLOCK_SOURCE_HIGHWAY ) { - write(*, 'HIGHWAY'); + write(*, 'Clock source HIGHWAY'); _clock_source = byte(_DIO4_CLOCK_SOURCE_TIMING_HIGHWAY); _out = byte(_DIO4_TH_OUTPUT_DISABLE);/*TT*/ } @@ -115,6 +163,50 @@ public fun DIO4HWInit(in _nid, in _board_id, in _ext_clock, in _rec_event, in _s return(0); } +/******************************************************************************/ +/* +** To reconfigure the PLL to lock on a external clock an +** internal divider has to changed. +** +** - Read current register value +** - Clear divider in lower 14 bits (default value is 0x00C8 (= 200) +** - External clock has to be divided down to 5kHz using an integer +** - divide value. For 2MHz this is 400 (= 0x190) +** - Write back new value +** RESET divider to default value if it was set on a previous initialization +*/ + + + _dwTemp = long(0); + _status = DIO4->DIO4_Tst_ReadRegister(val(_handle), val(long(0x3E0)), ref(_dwTemp)); + if(_status != 0) + { + if(_nid != 0) + DevLogErr(_nid, "Error reading register in DIO4 device, board ID = "// _board_id); + else + write(*, "Error reading register in DIO4 device, board ID = "// _board_id); + return(0); + } + +write(*,' Reg 0x3E0 ', ( long(_dwTemp) & 0xFFFFC000U)); +write(*,' Reg 0x3E0 ', (long(_dwTemp)) ); + +_dwTemp = _dwTemp & long(0xFFFFC000U); +_dwTemp = _dwTemp | long(0x000000C8U);/*Set default value to dovider*/ + + _status = DIO4->DIO4_Tst_WriteRegister(val(_handle), val(long(0x3E0)), val(long(_dwTemp))); + if(_status != 0) + { + if(_nid != 0) + DevLogErr(_nid, "Error writing register in DIO4 device, board ID = "// _board_id); + else + write(*, "Error writing register in DIO4 device, board ID = "// _board_id); + return(0); + } + +/******************************************************************************/ + + wait(1); /* @@ -133,6 +225,7 @@ public fun DIO4HWInit(in _nid, in _board_id, in _ext_clock, in _rec_event, in _s DIO4->DIO4_Close(val(_handle)); return(0); } + if (_bOK == _DIO4_CLOCK_SOURCE_OK) { /* ** Clock is present and PLL has locked diff --git a/tdi/RfxDevices/DIO4HWSetDClockChan.fun b/tdi/RfxDevices/DIO4HWSetDClockChan.fun index 6037b42869..4c9b5592b6 100644 --- a/tdi/RfxDevices/DIO4HWSetDClockChan.fun +++ b/tdi/RfxDevices/DIO4HWSetDClockChan.fun @@ -1,5 +1,5 @@ public fun DIO4HWSetDClockChan(in _nid, in _board_id, in _channel, in _trig_mode, in _frequency_1, - in _frequency_2, in _delay, in _duration, in _event, in _evTermCode) + in _frequency_2, in _delay, in _duration, in _event, in _cyclic, in _evTermCode) { private _DIO4_CLOCK_SOURCE_INTERNAL = 0x0; @@ -90,12 +90,23 @@ public fun DIO4HWSetDClockChan(in _nid, in _board_id, in _channel, in _trig_mode return(0); } +/* Phase Cyclic */ + + if(_cyclic) + _mode = byte(_DIO4_TC_CYCLIC); + else + _mode = byte(_DIO4_TC_SINGLE_SHOT); + + + + /* Phase setting */ _levels = [byte(1), byte(0), byte(1), byte(0)]; - _status = DIO4->DIO4_TC_SetPhaseSettings(val(_handle), val(byte(_channel + 1)), val(byte(_DIO4_TC_SINGLE_SHOT)), - val(byte(_DIO4_TC_INT_DISABLE)), _levels); + /*_status = DIO4->DIO4_TC_SetPhaseSettings(val(_handle), val(byte(_channel + 1)), val(byte(_DIO4_TC_SINGLE_SHOT)), val(byte(_DIO4_TC_INT_DISABLE)), _levels);*/ + _status = DIO4->DIO4_TC_SetPhaseSettings(val(_handle), val(byte(_channel + 1)), _mode, val(byte(_DIO4_TC_INT_DISABLE)), _levels); + if(_status != 0) { if(_nid != 0) diff --git a/tdi/RfxDevices/DIO4HWSetGClockChan.fun b/tdi/RfxDevices/DIO4HWSetGClockChan.fun index 4dc4ff4278..c994693578 100644 --- a/tdi/RfxDevices/DIO4HWSetGClockChan.fun +++ b/tdi/RfxDevices/DIO4HWSetGClockChan.fun @@ -1,5 +1,4 @@ -public fun DIO4HWSetGClockChan(in _nid, in _board_id, in _channel, in _trig_mode, in _frequency, - in _delay, in _duration, in _event, in _duty_cycle, in _cyclic, in _evTermCode) +public fun DIO4HWSetGClockChan(in _nid, in _board_id, in _channel, in _trig_mode, in _frequency, in _delay, in _duration, in _event, in _duty_cycle, in _cyclic, in _evTermCode) { @@ -104,8 +103,10 @@ public fun DIO4HWSetGClockChan(in _nid, in _board_id, in _channel, in _trig_mode _mode = byte(_DIO4_TC_SINGLE_SHOT); - +/* if(_duration > 214) +*/ + if(_duration > 420) { write(*, 'continuous'); _mode = byte(_mode | _DIO4_TC_TERMINATE_PHASE_2); @@ -125,22 +126,41 @@ public fun DIO4HWSetGClockChan(in _nid, in _board_id, in _channel, in _trig_mode /* Timing setting */ - _delay_cycles = long(_delay / 1E-7 + 0.5) - 1 ; +/* + _delay_cycles = long_unsigned(_delay / 1E-7 + 0.5) - 1 ; if(_delay_cycles < 0) _delay_cycles = 0; +*/ + _delay_cycles = 0; + if( _delay > 0 ) + _delay_cycles = long_unsigned(_delay * 10000000UL ); - _duration_cycles = long(_duration / 1E-7 + 0.5) - 1; + write(*, '_delay_cycles', _delay, _delay_cycles); + + +/* +Molto strano perche fare una divisione invece di una motiplicazione + _duration_cycles = long_unsigned(_duration / 1E-7 + 0.5) - 1; +*/ + _duration_cycles = 0; + if( _duration > 0 ) + _duration_cycles = long_unsigned( _duration * 10000000UL ); + +/* +Molto strano comunque un unsigned long viene rilevato negativo if(_duration_cycles < 0) _duration_cycles = 0; - write(*, '_duration_cycles', _duration_cycles); +*/ + + write(*, '_duration_cycles', _duration, _duration_cycles); _period = 1./_frequency; - _tot_cycles = long(_period / 1E-7 + 0.5); + _tot_cycles = long_unsigned(_period / 1E-7 + 0.5); - _cycles_1 = long(_tot_cycles * _duty_cycle / 100.) - 1; + _cycles_1 = long_unsigned(f_float(_tot_cycles) * f_float(_duty_cycle / 100.)) - 1; if(_cycles_1 < 0) _cycles_1 = 0; - _cycles_2 = long(_tot_cycles - _cycles_1 - 2); + _cycles_2 = long_unsigned(_tot_cycles - _cycles_1 - 2); if(_cycles_2 < 0) _cycles_2 = 0; @@ -150,18 +170,24 @@ public fun DIO4HWSetGClockChan(in _nid, in _board_id, in _channel, in _trig_mode _cycles_1--; _cycles_2--; */ - _cycles = [long(1), long(1), long(_cycles_1), long(_cycles_2)]; + _cycles = [long_unsigned(1), long_unsigned(1), long_unsigned(_cycles_1), long_unsigned(_cycles_2)]; write(*,'------>',_cycles); + if( _duration > 420 ) + { + _duration_cycles = 0; + } +/* Non capisco questo controllo lo commento if(_duration > 214) { _duration_cycles = 0; +*/ /* _duration_cycles = 99999999; -*/ } +*/ _status = DIO4->DIO4_TC_SetPhaseTiming(val(_handle), val(byte(_channel + 1)), _cycles, val(_delay_cycles), diff --git a/tdi/RfxDevices/NIADCClockSegment.fun b/tdi/RfxDevices/NIADCClockSegment.fun index 73c32075e9..b3ba1d6d4f 100755 --- a/tdi/RfxDevices/NIADCClockSegment.fun +++ b/tdi/RfxDevices/NIADCClockSegment.fun @@ -3,7 +3,7 @@ public fun NIADCClockSegment(in _clock, in _startIdx, in _endIdx, in _tAtIdx0, i _fact = 1; if(present( _period )) { - _fact = _period / _slope_of(_clock); + _fact = slope_of(_clock) / _period; } _segSmp = ( end_of(_clock) - begin_of(_clock) )/slope_of(_clock) * _fact; diff --git a/tdi/RfxDevices/TimingGetEvents.fun b/tdi/RfxDevices/TimingGetEvents.fun index 09ca41333d..7e94207684 100644 --- a/tdi/RfxDevices/TimingGetEvents.fun +++ b/tdi/RfxDevices/TimingGetEvents.fun @@ -4,8 +4,8 @@ public fun TimingGetEvents(out _event_names, out _event_codes) if( _expEvents == "spider" ) { - _event_names = ['T_START_SPIDER', 'T_BEAM_ON', 'T_SWITCH_OFF', 'T_BEAM_OFF', 'T_BREAK_DOWN']; - _event_codes = [1,2,3,4,5]; + _event_names = ['T_START_SPIDER', 'T_BEAM_ON', 'T_SWITCH_OFF', 'T_BEAM_OFF', 'T_BREAK_DOWN', 'EVENT_ACQ_1', 'EVENT_ACQ_2','T_PRE_SPIDER']; + _event_codes = [1,2,3,4,5,6,7,8]; } else { _event_names = ['CPST','CTST','CCT', 'T_START_RFX','T_START_PC','T_START_PM','T_START_PV','T_OPEN_PTSO','T_INSRT_PTCB','T_START_PR', 'T_CLOSE_PNSS', 'T_START_TF', 'T_START_GP', 'T_START_PLT', 'T_BLOW_OFF']; _event_codes = [1,2,3,4,5,6,7,8,9,10,11,12,13,33,14]; diff --git a/tdi/RfxDevices/caesiumSwitch.py b/tdi/RfxDevices/caesiumSwitch.py index 393af50558..9b9067cc7c 100644 --- a/tdi/RfxDevices/caesiumSwitch.py +++ b/tdi/RfxDevices/caesiumSwitch.py @@ -23,6 +23,11 @@ def caesiumSwitch(sigs, dt) : yIn = np.asarray([int(1) if v > 50 else int(0) for v in yIn]) + #Check if all RF power are OFF + if max(yIn) == 0 : + return Data.compile("build_signal($1,,$2)", np.asarray([0,0]), np.asarray([tIn[0],tIn[-1]])) + + #Compute the caesium enable signal with pre and post margin def checkEdge(val): # 0:y 1:y+1 2:y+2 3:t diff --git a/tdi/RfxDevices/getSpiderGasType.fun b/tdi/RfxDevices/getSpiderGasType.fun new file mode 100644 index 0000000000..9c1dcee913 --- /dev/null +++ b/tdi/RfxDevices/getSpiderGasType.fun @@ -0,0 +1,23 @@ +public fun getSpiderGasType(optional in _shot) +{ + if(present(_shot)) + treeopen("spider", _shot); + + _tank3000 = data(build_path("\\GVS_TSHOT::NB_SIGV_GISA_TA00_STY:VAL"))[0]; + _tank3090 = data(build_path("\\GVS_TSHOT::NB_SIGV_GISA_TA90_STY:VAL"))[0]; + + if(present(_shot)) + treeclose(); + + if( _tank3000 != 0 && _tank3090 != 0 ) + return ( "unknown" ); + + if ( _tank3000 == 1 ) return ("H2"); + if ( _tank3000 == 2 ) return ("D2"); + if ( _tank3090 == 1 ) return ("H2"); + if ( _tank3090 == 2 ) return ("D2"); + + return("NoGas"); + +} + diff --git a/tdi/RfxDevices/spiderBlipNumFromTime.py b/tdi/RfxDevices/spiderBlipNumFromTime.py new file mode 100644 index 0000000000..15e4c2fe7a --- /dev/null +++ b/tdi/RfxDevices/spiderBlipNumFromTime.py @@ -0,0 +1,21 @@ +def spiderBlipNumFromTime(time) : + + from MDSplus import Data + import numpy as np + + sigs = Data.compile('[\RF1_PREF:WAVE, \RF2_PREF:WAVE, \RF3_PREF:WAVE, \RF4_PREF:WAVE]') + s = Data.compile('caesiumSwitch($1, 0)', sigs) + + tIn = s.dim_of() + yIn = s.data() + + blipsOn = [(tIn[i], tIn[i+1]) if yIn[i] > 0 and yIn[i+1] > 0 else None for i in range(len(tIn) - 1)] + blipsOn = filter(lambda v: v is not None, blipsOn) + blipsIdx = np.asarray( [ 1 if bl[0] < time and bl[1] > time else 0 for bl in blipsOn ] ) + + if sum(blipsIdx) == 0: + return np.asarray( [ 0, len(blipsIdx)], dtype=np.int32 ) + else: + return np.asarray( [ np.nonzero(blipsIdx)[0][0]+1, len(blipsIdx)], dtype=np.int32 ) + + diff --git a/tdi/RfxDevices/spiderClockSegment.fun b/tdi/RfxDevices/spiderClockSegment.fun index ec614f360b..6e2c989277 100644 --- a/tdi/RfxDevices/spiderClockSegment.fun +++ b/tdi/RfxDevices/spiderClockSegment.fun @@ -1,11 +1,42 @@ public fun spiderClockSegment(in _clock, in _startIdx, in _endIdx, in _tAtIdx0, in _value) { + + + _segSmp = ( end_of(_clock) - begin_of(_clock) )/slope_of(_clock); + + if( size( _segSmp ) <= 1 ) + { + _dt = slope_of(_clock); + + _end = end_of(_clock); + /*if( _end == * )*/ + _end = _endIdx * _dt + _tAtIdx0; + + _begin = begin_of(_clock); + /*if( _begin == * )*/ + _begin = _startIdx * _dt + _tAtIdx0; + + _clock = make_range( _begin, _end, _dt); + + if( size( _segSmp ) == 1 ) + { + if( _value == 'start_time' ) + return ( _begin ); + if( _value == 'end_time' ) + return ( _end ); + if( _value == 'dim' ) + return ( _clock ); + } + } + /* TO BE cheked */ /* If all samples of the clock time base must be savede the _tAtIdx0 must be 0*/ /* ATTENTION: if some sample on the firt segment are skipped the function does not works properly */ _tAtIdx0 = 0; + /* _segSmp = ( end_of(_clock) - begin_of(_clock) )/slope_of(_clock); + */ _prevStSeg = 0; _prevEndSeg = 0;