/** Connect this plugin to an NDArray port driver; disconnect from any existing driver first, register
  * for callbacks if enabled. */
asynStatus NDPluginGather::connectToArrayPort(void)
{
    asynStatus status;
    asynInterface *pasynInterface;
    int enableCallbacks;
    char arrayPort[20];
    int arrayAddr;
    int i;
    NDGatherNDArraySource_t *pArraySrc = NDArraySrc_;
    static const char *functionName = "connectToArrayPort";

    getIntegerParam(NDPluginDriverEnableCallbacks, &enableCallbacks);
    for (i=0; i<maxPorts_; i++, pArraySrc++) {
        getStringParam(i, NDPluginDriverArrayPort, sizeof(arrayPort), arrayPort);
        getIntegerParam(i, NDPluginDriverArrayAddr, &arrayAddr);

        /* If we are currently connected to an array port cancel interrupt request */    
        if (pArraySrc->connectedToArrayPort) {
            status = setArrayInterrupt(0);
        }

        /* Disconnect the array port from our asynUser.  Ignore error if there is no device
         * currently connected. */
        pasynManager->disconnect(pArraySrc->pasynUserGenericPointer);
        pArraySrc->connectedToArrayPort = false;

        /* Connect to the array port driver if the arrayPort string is not zero-length */
        if (strlen(arrayPort) == 0) continue;
        status = pasynManager->connectDevice(pArraySrc->pasynUserGenericPointer, arrayPort, arrayAddr);
        if (status != asynSuccess) {
            asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
                      "%s::%s Error calling pasynManager->connectDevice to array port %s address %d, status=%d, error=%s\n",
                      driverName, functionName, arrayPort, arrayAddr, status, pArraySrc->pasynUserGenericPointer->errorMessage);
            return (status);
        }

        /* Find the asynGenericPointer interface in that driver */
        pasynInterface = pasynManager->findInterface(pArraySrc->pasynUserGenericPointer, asynGenericPointerType, 1);
        if (!pasynInterface) {
            asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
                      "%s::connectToPort ERROR: Can't find asynGenericPointer interface on array port %s address %d\n",
                      driverName, arrayPort, arrayAddr);
            return(asynError);
        }
        pArraySrc->pasynGenericPointer = (asynGenericPointer *)pasynInterface->pinterface;
        pArraySrc->asynGenericPointerPvt = pasynInterface->drvPvt;
        pArraySrc->connectedToArrayPort = true;
    }
    /* Enable or disable interrupt callbacks */
    status = setArrayInterrupt(enableCallbacks);

    return(status);
}   
BObjectImp* StorageExecutorModule::mf_FindStorageArea()
{
	const String* str = getStringParam(0);
	if ( str != NULL )
	{
		StorageArea *area = storage.find_area(str->value());

		if ( area )
			return new BApplicPtr(&storage_area_type, area);
	}
	return new BLong(0); // non-string passed, or not found.
}
Exemple #3
0
void mar345::getImageData()
{
    char fullFileName[MAX_FILENAME_LEN];
    size_t dims[2];
    int itemp;
    int imageCounter;
    NDArray *pImage;
    char statusMessage[MAX_MESSAGE_SIZE];
    char errorBuffer[MAX_MESSAGE_SIZE];
    FILE *input;
    const char *functionName = "getImageData";

    /* Inquire about the image dimensions */
    getStringParam(NDFullFileName, MAX_FILENAME_LEN, fullFileName);
    getIntegerParam(NDArraySizeX, &itemp); dims[0] = itemp;
    getIntegerParam(NDArraySizeY, &itemp); dims[1] = itemp;
    getIntegerParam(NDArrayCounter, &imageCounter);
    pImage = this->pNDArrayPool->alloc(2, dims, NDUInt16, 0, NULL);

    epicsSnprintf(statusMessage, sizeof(statusMessage), "Reading mar345 file %s", fullFileName);
    setStringParam(ADStatusMessage, statusMessage);
    callParamCallbacks();
    input = fopen(fullFileName, "rb");
    if (input == NULL) {
        (void) strerror_r(errno, errorBuffer, sizeof(errorBuffer));
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
            "%s%s: unable to open input file %s, error=%s\n",
            driverName, functionName, fullFileName, errorBuffer);
        return;
    }
    get_pck(input, (epicsInt16 *)pImage->pData);
    fclose(input);

    /* Put the frame number and time stamp into the buffer */
    pImage->uniqueId = imageCounter;
    pImage->timeStamp = this->acqStartTime.secPastEpoch + this->acqStartTime.nsec / 1.e9;

    /* Get any attributes that have been defined for this driver */        
    this->getAttributes(pImage->pAttributeList);

    /* Call the NDArray callback */
    /* Must release the lock here, or we can get into a deadlock, because we can
     * block on the plugin lock, and the plugin can be calling us */
    this->unlock();
    asynPrint(this->pasynUserSelf, ASYN_TRACE_FLOW, 
         "%s:%s: calling NDArray callback\n", driverName, functionName);
    doCallbacksGenericPointer(pImage, NDArrayData, 0);
    this->lock();

    /* Free the image buffer */
    pImage->release();
}
BObjectImp* PolSystemExecutorModule::mf_GetPackageByName()
{
    const String* pkgname;
    if ( !getStringParam(0, pkgname) )
        return new BError("Invalid parameter type.");

    //pkgname->toLower();
    Package* pkg = find_package(pkgname->value());
    if ( !pkg )
        return new BError("No package found by that name.");
    else
        return new PackageObjImp(PackagePtrHolder(pkg));
}
Exemple #5
0
int FastCCD::uploadFirmware(void){
  int _status = 0;

  char path[256];
  getStringParam(FastCCDFirmwarePath, sizeof(path), path);
  setIntegerParam(FastCCDFirmwareUpload, 1);

  // Power off the cin

  setStringParam(ADStatusMessage, "Powering CIN OFF");
  callParamCallbacks();
  if(cin_ctl_pwr(&cin_ctl_port, 0)){
    goto error;
  }

  sleep(5);
  getCameraStatus();

  // Power on the cin

  setStringParam(ADStatusMessage, "Powering CIN ON");
  callParamCallbacks();
  if(cin_ctl_pwr(&cin_ctl_port, 1)){
    goto error;
  }

  sleep(5);
  getCameraStatus();

  setStringParam(ADStatusMessage, "Uploading Firmware to CIN");
  callParamCallbacks();
  _status |= cin_ctl_load_firmware(&cin_ctl_port, 
                                  &cin_ctl_port_stream, path);
 
  if(!_status){
    _status |= cin_ctl_set_fabric_address(&cin_ctl_port, (char *)cinFabricIP);
    _status |= cin_data_send_magic();
  }

  setIntegerParam(FastCCDFirmwareUpload, 0);

error:

  if(_status){
    setStringParam(ADStatusMessage, "ERROR Uploading Firmware");
  } else {
    setStringParam(ADStatusMessage, "Firmware uploaded to CIN");
  }

  return _status;
}
Exemple #6
0
/** Base method for opening a file
  * Creates the file name with NDPluginBase::createFileName, then calls the pure virtual function openFile
  * in the derived class. */
asynStatus NDPluginFile::openFileBase(NDFileOpenMode_t openMode, NDArray *pArray)
{
    /* Opens a file for reading or writing */
    asynStatus status = asynSuccess;
    char fullFileName[MAX_FILENAME_LEN];
    char tempSuffix[MAX_FILENAME_LEN];
    char errorMessage[256];
    static const char* functionName = "openFileBase";

    if (this->useAttrFilePrefix)
        this->attrFileNameSet();

    setIntegerParam(NDFileWriteStatus, NDFileWriteOK);
    setStringParam(NDFileWriteMessage, "");
    status = (asynStatus)createFileName(MAX_FILENAME_LEN, fullFileName);
    if (status) {
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, 
              "%s::%s error creating full file name, fullFileName=%s, status=%d\n", 
              driverName, functionName, fullFileName, status);
        setIntegerParam(NDFileWriteStatus, NDFileWriteError);
        setStringParam(NDFileWriteMessage, "Error creating full file name");
        return(status);
    }
    setStringParam(NDFullFileName, fullFileName);
    
    getStringParam(NDFileTempSuffix, sizeof(tempSuffix), tempSuffix);
    if ( *tempSuffix != 0 && 
         (strlen(fullFileName) + strlen(tempSuffix)) < sizeof(fullFileName) ) {
        strcat( fullFileName, tempSuffix );
    }

    /* Call the openFile method in the derived class */
    /* Do this with the main lock released since it is slow */
    this->unlock();
    epicsMutexLock(this->fileMutexId);
    this->registerInitFrameInfo(pArray);
    status = this->openFile(fullFileName, openMode, pArray);
    if (status) {
        epicsSnprintf(errorMessage, sizeof(errorMessage)-1, 
            "Error opening file %s, status=%d", fullFileName, status);
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, 
              "%s::%s %s\n", 
              driverName, functionName, errorMessage);
        setIntegerParam(NDFileWriteStatus, NDFileWriteError);
        setStringParam(NDFileWriteMessage, errorMessage);
    }
    epicsMutexUnlock(this->fileMutexId);
    this->lock();
    
    return(status);
}
void ReadASCII::readFilePoll(void)
{
	//Thread to poll the file used in the PID lookup and update the array of values when the file is modified
	char localDir[DIR_LENGTH], dirBase[DIR_LENGTH];
	asynStatus status;

	while (1) {
		
		//wait for a file change
		epicsThreadSleep(2.0);
		
		if (true == fileBad)
			continue;

		lock();

		//get directory in this thread
		getStringParam(P_DirBase, DIR_LENGTH, dirBase);
		getStringParam(P_Dir, DIR_LENGTH, localDir);

		//release lock
		unlock();

		strcat(dirBase, "/");
		strcat(dirBase, localDir);

		if (false == isModified(dirBase))
		{
			continue;
		}

		lock();

		status = readFile(dirBase);

		unlock();
	}
}
Exemple #8
0
/** Called when asyn clients call pasynOctet->write().
  * This function performs actions for some parameters, including AttributesFile.
  * For all parameters it sets the value in the parameter library and calls any registered callbacks..
  * \param[in] pasynUser pasynUser structure that encodes the reason and address.
  * \param[in] value Address of the string to write.
  * \param[in] nChars Number of characters to write.
  * \param[out] nActual Number of characters actually written.
  */
asynStatus NDPosPlugin::writeOctet(asynUser *pasynUser, const char *value, size_t nChars, size_t *nActual)
{
  int addr=0;
  int function = pasynUser->reason;
  asynStatus status = asynSuccess;
  char *fileName = new char[MAX_POS_STRING_LEN];
  fileName[MAX_POS_STRING_LEN - 1] = '\0';
  const char *functionName = "writeOctet";

  status = getAddress(pasynUser, &addr); if (status != asynSuccess) return(status);
  // Set the parameter in the parameter library.
  status = (asynStatus)setStringParam(addr, function, (char *)value);
  if (status != asynSuccess) return(status);

  if (function == NDPos_Filename){
    // Read the filename parameter
    getStringParam(NDPos_Filename, MAX_POS_STRING_LEN-1, fileName);
    // Now validate the XML
    NDPosPluginFileReader fr;
    if (fr.validateXML(fileName) == asynSuccess){
      setIntegerParam(NDPos_FileValid, 1);
    } else {
      setIntegerParam(NDPos_FileValid, 0);
      status = asynError;
    }
    // If the status of validation is OK then load the file
    if (status == asynSuccess){
      // Call the loadFile function
      status = loadFile();
    }
  } else if (function < FIRST_NDPOS_PARAM){
    // If this parameter belongs to a base class call its method
    status = NDPluginDriver::writeOctet(pasynUser, value, nChars, nActual);
  }

  // Do callbacks so higher layers see any changes
  callParamCallbacks(addr, addr);

  if (status){
    epicsSnprintf(pasynUser->errorMessage, pasynUser->errorMessageSize,
                  "%s:%s: status=%d, function=%d, value=%s",
                  driverName, functionName, status, function, value);
  } else {
    asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
              "%s:%s: function=%d, value=%s\n",
              driverName, functionName, function, value);
  }
  *nActual = nChars;
  return status;
}
/** Checks whether the directory specified NDFilePath parameter exists.
  * 
  * This is a convenience function that determines the directory specified NDFilePath parameter exists.
  * It sets the value of NDFilePathExists to 0 (does not exist) or 1 (exists).  
  * It also adds a trailing '/' character to the path if one is not present.
  * Returns a error status if the directory does not exist.
  */
asynStatus asynNDArrayDriver::checkPath()
{
    asynStatus status;
    std::string filePath;
    int pathExists;
    
    getStringParam(NDFilePath, filePath);
    if (filePath.size() == 0) return asynSuccess;
    pathExists = checkPath(filePath);
    status = pathExists ? asynSuccess : asynError;
    setStringParam(NDFilePath, filePath);
    setIntegerParam(NDFilePathExists, pathExists);
    return status;   
}
Exemple #10
0
/** Check whether the attributes defining the filename has changed since last write.
 * If this is the first frame (NDFileNumCaptured == 1) then the file is opened.
 * For other frames we check whether the attribute file name or number has changed
 * since last write. If this is the case then the current file is closed a new one opened.
 */
asynStatus NDPluginFile::attrFileNameCheck()
{
    asynStatus status = asynSuccess;
    NDAttribute *NDattrFileName, *NDattrFileNumber;
    int compare, attrFileNumber, ndFileNumber;
    char attrFileName[MAX_FILENAME_LEN];
    char ndFileName[MAX_FILENAME_LEN];
    int numCapture, numCaptured;
    bool reopenFile = false;

    if (!this->useAttrFilePrefix) return status;

    getIntegerParam(NDFileNumCapture, &numCapture);
    getIntegerParam(NDFileNumCaptured, &numCaptured);

    if (numCaptured == 1) {
        status = this->openFileBase(NDFileModeWrite | NDFileModeMultiple, this->pArrays[0]);
        return status;
    }

    NDattrFileName   = this->pArrays[0]->pAttributeList->find(FILEPLUGIN_NAME);
    if (NDattrFileName != NULL) {
        NDattrFileName->getValue(NDAttrString, attrFileName, MAX_FILENAME_LEN);
        getStringParam(NDFileName, MAX_FILENAME_LEN, ndFileName);
        compare = epicsStrnCaseCmp(attrFileName, ndFileName, strlen(attrFileName));
        if (compare != 0)
            reopenFile = true;
    }

    NDattrFileNumber = this->pArrays[0]->pAttributeList->find(FILEPLUGIN_NUMBER);
    if (NDattrFileNumber != NULL)
    {
        NDattrFileNumber->getValue(NDAttrInt32, (void*) &attrFileNumber, 0);
        getIntegerParam(NDFileNumber, &ndFileNumber);
        if (ndFileNumber != attrFileNumber)
        {
            reopenFile = true;
            setIntegerParam( NDFileNumber, attrFileNumber);
        }
    }
    asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "attrFileNameCheck: name=%s(%s) num=%d (%s) reopen=%d\n",
            attrFileName, ndFileName, attrFileNumber, NDattrFileNumber->getSource(), (int)reopenFile );
    if (reopenFile)
    {
        this->closeFileBase();
        setIntegerParam(NDFileNumCaptured, 1);
        status = this->openFileBase(NDFileModeWrite | NDFileModeMultiple, this->pArrays[0]);
    }
    return status;
}
/* default constructor */
GStreamerFilter::GStreamerFilter (
  MediaSet &mediaSet, std::shared_ptr<MediaPipeline> parent,
  const std::map<std::string, KmsMediaParam> &params)
  : Filter (mediaSet, parent, g_KmsMediaGStreamerFilterType_constants.TYPE_NAME,
            params)
{
  std::string commandLine, command, rest_token;
  GstElement *gstreamerFilter;

  getStringParam (commandLine, params,
                  g_KmsMediaGStreamerFilterType_constants.CONSTRUCTOR_PARAM_GSTREAMER_COMMAND);

  command = commandLine.substr (0, commandLine.find (' ') );

  GST_DEBUG ("Command %s", command.c_str() );

  element = gst_element_factory_make ("filterelement", NULL);

  g_object_set (element, "filter-factory", command.c_str(), NULL);
  g_object_ref (element);
  gst_bin_add (GST_BIN (parent->pipeline), element);
  gst_element_sync_state_with_parent (element);

  g_object_get (G_OBJECT (element), "filter", &gstreamerFilter, NULL);

  if (gstreamerFilter == NULL) {
    KmsMediaServerException except;

    createKmsMediaServerException (except,
                                   g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_TYPE_NOT_FOUND,
                                   "Media Object type not found");
    throw except;
  }

  this->filter = gstreamerFilter;
  g_object_unref (gstreamerFilter);

  rest_token = commandLine.substr (command.length(), commandLine.length() - 1);

  if (rest_token.front() == ' ') {
    rest_token = rest_token.substr (rest_token.find_first_not_of (" "),
                                    rest_token.length() - 1);
  }

  if (rest_token.length() != 0) {
    setCommandProperties (rest_token);
  }

}
Exemple #12
0
void NDFileNexus::loadTemplateFile() {
  bool loadStatus;
  int addr = 0;
  char fullFilename[2*MAX_FILENAME_LEN] = "";
  char template_path[MAX_FILENAME_LEN] = "";
  char template_file[MAX_FILENAME_LEN] = "";
  static const char *functionName = "loadTemplateFile";

  /* get the filename to be used for nexus template */
  getStringParam(addr, NDFileNexusTemplatePath, sizeof(template_path), template_path);
  getStringParam(addr, NDFileNexusTemplateFile, sizeof(template_file), template_file);
  sprintf(fullFilename, "%s%s", template_path, template_file);
  if (strlen(fullFilename) == 0) return;

  /* Load the Nexus template file */
  loadStatus = this->configDoc.LoadFile(fullFilename);

  if (loadStatus != true ){
    asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
              "%s:%s: Parameter file %s is invalid\n",
              driverName, functionName, fullFilename);
    setIntegerParam(addr, NDFileNexusTemplateValid, 0);
    callParamCallbacks(addr, addr);
    return;
  }
  else {
    asynPrint(this->pasynUserSelf, ASYN_TRACE_FLOW,
              "%s:%s: Parameter file %s was successfully loaded\n",
              driverName, functionName, fullFilename);
    setIntegerParam(addr, NDFileNexusTemplateValid, 1);
    callParamCallbacks(addr, addr);
  }

  this->rootNode = this->configDoc.RootElement();

}
Exemple #13
0
BObjectImp* FileAccessExecutorModule::mf_AppendToFile()
{
	const String* filename;
	ObjArray* contents;
	if (!getStringParam( 0, filename ) ||
		!getObjArrayParam( 1, contents ))
	{
		return new BError( "Invalid parameter type" );
	}

	const Package* outpkg;
	string path;
	if (!pkgdef_split( filename->value(), exec.prog()->pkg, &outpkg, &path ))
		return new BError( "Error in filename descriptor" );

	if (path.find( ".." ) != string::npos)
		return new BError( "No parent path traversal please." );

	if (!HasAppendAccess( exec.prog()->pkg, outpkg, path ))
		return new BError( "Access denied" );

	string filepath;
	if (outpkg == NULL)
		filepath = path;
	else
		filepath = outpkg->dir() + path;

	ofstream ofs( filepath.c_str(), ios::out|ios::app );

	if (!ofs.is_open())
		return new BError( "Unable to open file: " + filepath );

	for( unsigned i = 0; i < contents->ref_arr.size(); ++i )
	{
		BObjectRef& ref = contents->ref_arr[i];
		BObject* obj = ref.get();
		if (obj != NULL)
		{
			ofs << (*obj)->getStringRep();
		}
		ofs << endl;
	}
	if (ofs.fail())
		return new BError( "Error during write." );

	return new BLong(1);
}
BObjectImp* PolSystemExecutorModule::mf_DeleteRealm(/*name*/)
{
    const String* realm_name;
    if ( !(getStringParam(0, realm_name)))
        return new BError("Invalid parameter");
    Realm* realm = find_realm(realm_name->value());
    if ( !realm )
        return new BError("Realm not found.");
    if ( !realm->is_shadowrealm )
        return new BError("Realm is not a ShadowRealm.");
    if ( realm->mobile_count > 0 )
        return new BError("Mobiles in Realm.");
    if ( realm->toplevel_item_count > 0 )
        return new BError("Items in Realm.");
    remove_realm(realm_name->value());
    return new BLong(1);
}
/** Checks whether the directory specified NDFilePath parameter exists.
  * 
  * This is a convenience function that determinesthe directory specified NDFilePath parameter exists.
  * It sets the value of NDFilePathExists to 0 (does not exist) or 1 (exists).  
  * It also adds a trailing '/' character to the path if one is not present.
  * Returns a error status if the directory does not exist.
  */
asynStatus asynNDArrayDriver::checkPath()
{
    /* Formats a complete file name from the components defined in NDStdDriverParams */
    asynStatus status = asynError;
    char filePath[MAX_FILENAME_LEN];
    char lastChar;
    int hasTerminator=0;
    struct stat buff;
    int istat;
    size_t len;
    int isDir=0;
    int pathExists=0;
    
    getStringParam(NDFilePath, sizeof(filePath), filePath);
    len = strlen(filePath);
    if (len == 0) return(asynSuccess);
    /* If the path contains a trailing '/' or '\' remove it, because Windows won't find
     * the directory if it has that trailing character */
    lastChar = filePath[len-1];
#ifdef _WIN32
    if ((lastChar == '/') || (lastChar == '\\'))
#else
    if (lastChar == '/') 
#endif
    {
        filePath[len-1] = 0;
        len--;
        hasTerminator=1;
    }
    istat = stat(filePath, &buff);
    if (!istat) isDir = (S_IFDIR & buff.st_mode);
    if (!istat && isDir) {
        pathExists = 1;
        status = asynSuccess;
    }
    /* If the path did not have a trailing terminator then add it if there is room */
    if (!hasTerminator) {
        if (len < MAX_FILENAME_LEN-2) strcat(filePath, delim);
        setStringParam(NDFilePath, filePath);
    }
    setIntegerParam(NDFilePathExists, pathExists);
    return status;   
}
Exemple #16
0
BObjectImp* FileAccessExecutorModule::mf_FileExists()
{
	const String* filename;
	if ( !getStringParam(0, filename) )
		return new BError("Invalid parameter type.");

	const Package* outpkg;
	string path;
	if ( !pkgdef_split(filename->value(), exec.prog()->pkg, &outpkg, &path) )
		return new BError("Error in filename descriptor.");

	if ( path.find("..") != string::npos )
		return new BError("No parent path traversal allowed.");
	
	string filepath;
	if ( outpkg == NULL )
		filepath = path;
	else
		filepath = outpkg->dir() + path;

	return new BLong(FileExists(filepath));
}
asynStatus
NDFileFITS::WriteKeys(fitsfile *fitsFilePtr, int* fitsStatus) {
  *fitsStatus = 0;
  std::ifstream fHeader;
  char filePath[MAX_PATH] = {0};
  *fitsStatus = getStringParam(NDFITSFileHeaderFullPathname, sizeof(filePath), filePath); 

  if (*fitsStatus) return asynSuccess;
  fHeader.open(filePath, std::ios_base::in);
  if(fHeader.fail()) 
    return asynSuccess; // If the file does not exists there is nothing to add
  
  char lineBuf[256], keyword[FLEN_KEYWORD], value[FLEN_VALUE], comment[FLEN_COMMENT];
  char *pToken;
  char *context	= NULL;
  
  while (fHeader.getline(lineBuf, sizeof(lineBuf), '\n')) {
    if (strstr(lineBuf, "//")) continue;// It is a comment
    pToken= strtok_s(lineBuf, "\n\t ", &context);
    if (!pToken) continue;// It is an empty line
    strncpy_s(keyword, sizeof(keyword), pToken, _TRUNCATE);
    pToken= strtok_s(0, "\n\t ", &context);
    if (!pToken) continue;// No value specified.. skip entire line
    strncpy_s(value, sizeof(value), pToken, _TRUNCATE);
    pToken= strtok_s(0, "\n", &context);
    if (pToken)
      strncpy_s(comment, sizeof(comment), pToken, _TRUNCATE);
    else
      strncpy_s(comment, sizeof(comment), "", _TRUNCATE);
      
	  fits_update_key(fitsFilePtr, CFITSIO_TSTRING, keyword, value, comment, fitsStatus);
  }
  
  fits_close_file(fitsFilePtr, fitsStatus); // close the fits file
  fHeader.close();
  if(*fitsStatus) return asynError;
  return asynSuccess;  
}
bool DvornikovDifferentiator::initFilter(const ParameterMap& params,
		const StreamInfo& in) {
	// get order
	int order = 0;
	string orderStr = getStringParam("DDOrder",params);
	if (orderStr[orderStr.size()-1]=='s')
	{
		double dur = strtod(orderStr.substr(0,orderStr.size()-1).c_str(),NULL);
		dur /= 2;
		order = (int) floor(dur*in.sampleRate/in.sampleStep);
		order = 2 * order + 1;
	} else {
		order = atoi(orderStr.c_str());
		if (order%2)
		{
			cerr << "ERROR: DDOrder parameter must be odd in " << getIdentifier() << " component !" << endl;
			return false;
		}
	}
	// build filter
	m_length = order;
	m_filter = new double[order];
	for (int i=0;i<order;i++)
		m_filter[i] = 0;
	int halfOrder = (order - 1) / 2;
	m_delay = halfOrder;
	for (int m=1;m<=halfOrder;m++)
	{
		double r1 = 1;
		for (int k=1;k<=halfOrder;k++)
			if (k!=m)
				r1 *= 1 - pow2((double)m/k);
		r1 = 1 / (2*r1*m);
		m_filter[halfOrder-m] = -r1;
		m_filter[halfOrder+m] = r1;
	}
	return true;
}
Exemple #19
0
int FastCCD::uploadConfig(int status, int path){

  int _status = 0;
  char _path[256];

  getStringParam(path, sizeof(_path), _path);
  setIntegerParam(status, 1);
  setStringParam(ADStatusMessage, "Uploading Config File");
  callParamCallbacks();

  _status = cin_ctl_load_config(&cin_ctl_port, _path);

  setIntegerParam(status, 0);
  if(!_status){
    setStringParam(ADStatusMessage, "Config Uploaded to CIN");
    setParamStatus(path, asynSuccess);
  } else {
    setStringParam(ADStatusMessage, "ERROR Uploading Config to CIN");
    setParamStatus(path, asynError);
  }

  return _status;
}
Exemple #20
0
BObjectImp* FileAccessExecutorModule::mf_CreateDirectory()
{
	const String* dirname;
	if (!getStringParam( 0, dirname ))
		return new BError( "Invalid parameter type" );

	const Package* outpkg;
	string path;
	if (!pkgdef_split( dirname->value(), exec.prog()->pkg, &outpkg, &path ))
		return new BError( "Error in dirname descriptor" );
	if (path.find( ".." ) != string::npos)
		return new BError( "No parent path traversal please." );

	if (outpkg != NULL)
		path = outpkg->dir() + path;
	path = normalized_dir_form(path);
	if ( IsDirectory( path.c_str() ) )
		return new BError( "Directory already exists." );
	int res = make_dir(path.c_str());
	if (res != 0)
		return new BError( "Could not create directory." );
	return new BLong(1);
}
Exemple #21
0
BObjectImp* UOExecutorModule::mf_MoveObjectToLocation(/*object, x, y, z, realm, flags*/)
{
	UObject* obj;
	unsigned short x, y;
	short z;
	long flags;
	const String* realm_name;

	// Initialize variables
	if ( !(getUObjectParam( exec, 0, obj) &&
			getParam(1, x) &&
			getParam(2, y) &&
			getParam(3, z, WORLD_MIN_Z, WORLD_MAX_Z) &&
			getStringParam(4, realm_name) &&
			getParam(5, flags)) )
	{
			return new BError("Invalid parameter");
    }
	Realm* realm = find_realm(realm_name->value());
	if( !realm ) 
		return new BError("Realm not found.");
	else if( !realm->valid(x, y, z) ) 
		return new BError("Invalid coordinates for realm.");
    
	if ( obj->script_isa(POLCLASS_MOBILE) )
		return internal_MoveCharacter(static_cast<Character*>(obj), x, y, z, flags, realm);
	else if ( obj->script_isa(POLCLASS_BOAT) )
		return internal_MoveBoat(static_cast<UBoat*>(obj), x, y, z, flags, realm);
	else if ( obj->script_isa(POLCLASS_MULTI) )
		return new BError("Can't move multis at this time.");
	else if ( obj->script_isa(POLCLASS_CONTAINER) )
		return internal_MoveContainer(static_cast<UContainer*>(obj), x, y, z, flags, realm);
	else if ( obj->script_isa(POLCLASS_ITEM) )
		return internal_MoveItem(static_cast<Item*>(obj), x ,y ,z , flags, realm);
	else
		return new BError("Can't handle that object type.");
}
Exemple #22
0
BObjectImp* FileAccessExecutorModule::mf_OpenBinaryFile()
{
	const String* filename;
	unsigned short mode,bigendian;
	if ((!getStringParam( 0, filename )) ||
		(!getParam(1,mode)) ||
		(!getParam(2,bigendian)))
		return new BError( "Invalid parameter type" );

	const Package* outpkg;
	string path;
	if (!pkgdef_split( filename->value(), exec.prog()->pkg, &outpkg, &path ))
		return new BError( "Error in filename descriptor" );

	if (path.find( ".." ) != string::npos)
		return new BError( "No parent path traversal please." );

	if (mode & 0x01)
	{
		if (!HasReadAccess( exec.prog()->pkg, outpkg, path ))
			return new BError( "Access denied" );
	}
	if (mode & 0x02)
	{
		if (!HasWriteAccess( exec.prog()->pkg, outpkg, path ))
			return new BError( "Access denied" );
	}

	string filepath;
	if (outpkg == NULL)
		filepath = path;
	else
		filepath = outpkg->dir() + path;

	return new BBinaryfile( filepath, mode, bigendian==1?true:false );

}
Exemple #23
0
int main(int argc, char *argv[])
{
  char line[80];
  char *xs, *ys, *zs, *fvis;
  int i, j, k;
  int x_dim, y_dim, z_dim;
  double fvi;
  double _box_x, _box_y, _box_z;
  char *outfile_name = "outfile.tif";

  int sampleperpixel = 4;

  char *image;

  instream = stdin;

  setCommandLineParameters(argc, argv);

  if (getFlagParam("-usage"))
  {
    printf("usage:  fvi2tif       -box lll mmm nnn \n");
    printf("                      -o [outfile.tif] \n"); 
    printf("                      < file.fvi\n");
    exit(0);
  }
  getStringParam("-o", &outfile_name);
  printf("using %s outfile...\n", outfile_name);

  getVectorParam("-box", &_box_x, &_box_y, &_box_z);
  x_dim = floor(_box_x);
  y_dim = floor(_box_y);
  z_dim = floor(_box_z);

//    else if (!strcmp(argv[i], "-o")) outfile_name = argv[++i];
//    else if (!strcmp(argv[i], "-box")) {
//      x_dim = atoi(argv[++i]);
//      y_dim = atoi(argv[++i]);
//      z_dim = atoi(argv[++i]);
//      printf("xyz = %d\t%d\t%d\n", x_dim, y_dim, z_dim );
//    }
//  }

  image = (char*)malloc(x_dim * y_dim * z_dim * sampleperpixel);

  for (k=0; k<z_dim; k++)
  for (j=0; j<y_dim; j++)
  for (i=0; i<x_dim; i++)
  {
    fgets(line, 80, instream);
    if (feof(instream)) break;

    xs = strtok(line, "\t");
    ys = strtok(NULL, "\t");
    zs = strtok(NULL, "\t");
    fvis = strtok(NULL, "\n");

    fvi = strtod(fvis, NULL);

    int voxel = sampleperpixel * (i + j*x_dim + k*x_dim*y_dim);
    char fvid = (char)floor(fvi*256);
    image[0 + voxel] = 0;	// RED
    image[1 + voxel] = fvid;	// GREEN
    image[2 + voxel] = 0;	// BLUE
//    image[3 + voxel] = 255;	
    image[3 + voxel] = 0;	// ALPHA
  }

  makeTIFF(outfile_name, x_dim, y_dim, z_dim, image, sampleperpixel);
}
/** Called when asyn clients call pasynOctet->write().
 * Catch parameter changes.  If the user changes the path or name of the template file
 * load the new template file.
 * \param[in] pasynUser pasynUser structure that encodes the reason and address.
 * \param[in] value Address of the string to write.
 * \param[in] nChars Number of characters to write.
 * \param[out] nActual Number of characters actually written. */
asynStatus NDFileHDF5XML::writeOctet(asynUser *pasynUser, const char *value,
      size_t nChars, size_t *nActual)
{
   int addr = 0;
   int function = pasynUser->reason;
   asynStatus status = asynSuccess;
   const char *functionName = "writeOctet";
char pathstr[512];

   status = getAddress(pasynUser, &addr);
   if (status != asynSuccess)
      return (status);
   /* Set the parameter in the parameter library. */
   status = (asynStatus) setStringParam(addr, function, (char *) value);

   char mesx[256];
   char *mesx2;
   
   getParamName(function, (const char**)&mesx2);
   
     sprintf(longmsg,"NDFileHDF5XML::writeOctet, param=%s, value=%s",mesx2,value);
   lf.log(longmsg);
   
  
    if (function == NDFilePath) {

            int is_makedirs;
            int statx;
            
            getStringParam(NDFilePath, sizeof(pathstr), pathstr);
            getIntegerParam(NDFileHDF5XML_createDirs,&is_makedirs);
            statx = recursePath(pathstr, (bool)is_makedirs);
            printf("HDF5 Recurse path: statis = %d\n",statx);

            if (statx==0)
                setIntegerParam(NDFilePathExists, 1);
            else
                setIntegerParam(NDFilePathExists, 0);


    } 
   
   if (function == NDFileHDF5XML_templatepath)
   {
      loadTemplateFile();
   }
   if (function == NDFileHDF5XML_templatefile)
   {
      loadTemplateFile();
   }
   else
   {
      /* If this parameter belongs to a base class call its method */
      status = NDPluginFile::writeOctet(pasynUser, value, nChars, nActual);
   }

   /* Do callbacks so higher layers see any changes */
   status = (asynStatus) callParamCallbacks(addr, addr);

   if (status)
      epicsSnprintf(pasynUser->errorMessage, pasynUser->errorMessageSize,
            "%s:%s: status=%d, function=%d, value=%s", driverName, functionName,
            status, function, value);
   else
      asynPrint(pasynUser, ASYN_TRACEIO_DRIVER,
            "%s:%s: function=%d, value=%s\n", driverName, functionName,
            function, value);
   *nActual = nChars;
   return status;
}
void NDFileHDF5XML::loadTemplateFile(void)
{
   bool loadStatus = false;
   int status = asynSuccess;
   int addr = 0;
   static const char *functionName = "loadTemplateFile";

   
   lf.log("NDFileHDF5XML::loadTemplateFile");
/*   if (lockConfigFile() ==asynSuccess){
      /* get the filename to be used for nexus template */
      status = getStringParam(addr, NDFileHDF5XML_templatepath,
            sizeof(template_path), template_path);
      status = getStringParam(addr, NDFileHDF5XML_templatefile,
            sizeof(template_file), template_file);

      delete (configDoc);
      configDoc = new TiXmlDocument();

      if ( strstr(template_file, "<?xml") == NULL) {
         sprintf(template_fullname, "%s%s", template_path, template_file);
         if (strlen(template_fullname) == 0)
            return;

         /* Load the HDF template file */
        //!! lock();
         loadStatus = configDoc->LoadFile(template_fullname);
         
         lf.log("Load template from file");
       //!!  unlock();
      }
      else {
         //printf("Template contents:\n%s\n", template_file);
       //!! lock();
         configDoc->Parse(template_file, 0, TIXML_ENCODING_UTF8);
         lf.log("Parse xml in the pv");
       //!!  unlock();
         if (configDoc->Error()){
            loadStatus = false;
            lf.log("parsing error in xml");
         }
         else {
            loadStatus = true;
            lf.log("parsed xml correctly");
         }
      }
      if (loadStatus != true)
      {
         lf.log("Cound not load xml");
         asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
               "%s:%s: Parameter file %s is invalid\n", driverName, functionName,
               template_fullname);
         asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
               "%s:%s: XML parsing message on (row, col) (%d,%d)\n%s\n", driverName, functionName,
               configDoc->ErrorRow(), configDoc->ErrorCol(), configDoc->ErrorDesc());
         setIntegerParam(addr, NDFileHDF5XML_TemplateValid, 0);
         callParamCallbacks(addr, addr);

         asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
               "xml not found- use default\n");
         loadStatus = configDoc->Parse(default_xml);

         return;
      }
      else
      {
         lf.log("loaded xml");
         asynPrint(this->pasynUserSelf, ASYN_TRACE_FLOW,
               "%s:%s: Parameter file %s was successfully loaded\n", driverName,
               functionName, template_fullname);
         setIntegerParam(addr, NDFileHDF5XML_TemplateValid, 1);
         callParamCallbacks(addr, addr);
      }
/*      unlockConfigFile();
   }
   else
   {
      asynPrint(this->pasynUserSelf, ASYN_TRACE_FLOW,
            "%s:%s: Parameter file %s is locked.  Cannot load a new file now.\n", driverName,
            functionName, template_fullname);
      setIntegerParam(addr, NDFileHDF5XML_TemplateValid, 0);
      callParamCallbacks(addr, addr);
   }
*/
}
/** This is called to open a TIFF file.
 */
asynStatus NDFileHDF5XML::openFile(const char *fileName,
      NDFileOpenMode_t openMode, NDArray *pArray)
{
   char str0[256];
   char str1[256];
   int fn0, fn1;
   int is_update;
   static const char *functionName = "openFile";
/*   if (lockConfigFile() != asynSuccess)
   {
      return asynError;
   }
*/
   //enable retrig capture strat
   capture_trig = 1;

   
   lf.log("NDFileHDF5XML::openFile");
   
   
   this->openModesave = openMode;

   /* We don't support reading yet */
   if (openMode & NDFileModeRead)
      return (asynError);

   /* We don't support opening an existing file for appending yet */
   if (openMode & NDFileModeAppend)
      return (asynError);

   /* Set the next record in the file to 0 */

   //num_bad_fpgaheads=0;
   this->nextRecord = 0;

#if 0
   getStringParam(NDFileName,255,str0);
   getStringParam(NDFilePath,255,str1);
   getIntegerParam(NDFileNumber,&fn0);
   getIntegerParam(NDFileNumCapture,&fn1);

   // this is a kludge because base class uincs the NDFileNumber for us. we are negating that so
   // we can keep track ourselves here.
   getIntegerParam(NDAutoIncrement,&is_update);
   if (is_update==1 && filenum_kludge==0)
   {
      fn0=fn0-1;
      setIntegerParam(NDFileNumber,fn0);
   }

// keep track of filenumber so if base class messes it up we are not consused...
   //            last_filenumber = fn0;

   if (openMode&NDFileModeMultiple)
   {

      sprintf(hdf_fullname,"%s%s_%05d_%05d.hdf",str1,str0,fn0,fn1);
   }
   else
   {
      sprintf(hdf_fullname,"%s%s_%05d.hdf",str1,str0,fn0);
   }

#endif
   strcpy(hdf_fullname, fileName);

   loadTemplateFile();

   hdf_interface->pArray = pArray;

   hdfSetup->setFileName(hdf_fullname);
   hdfSetup->setLeaveOpen(true);
  //!!  lock();
   if (!configDoc->Accept(hdfSetup)){
      return (asynError);
      is_file_open = false;
   }
   else{
      is_file_open = true;
   }
   //!!unlock();
   hdf5Writer->setFileName(hdf_fullname);
   hdf5Writer->setLeaveOpen(true);
   hdf5Writer->setHDFFilePtr(hdfSetup->getHDFFilePtr());
   hdf5Writer->setHDFAccess(hdf_append);

   hdf5Closer->setFileName(hdf_fullname);
   hdf5Closer->setLeaveOpen(false);
   hdf5Closer->setHDFFilePtr(hdfSetup->getHDFFilePtr());
   hdf5Closer->setHDFAccess(hdf_append);

   setStringParam(NDFullFileName, hdf_fullname);

   return (asynSuccess);
}
asynStatus FileList::updateList()
{
	char dirBase[INPUT_WAVEFORM_LIM];
	char search[INPUT_WAVEFORM_LIM];
	int caseSense;
	std::list<std::string> files;
	int status = asynSuccess;
	std::string out;

	lock();

	//get all files in directory
	status |= getStringParam(P_DirBase, INPUT_WAVEFORM_LIM, dirBase);

	if (getFileList(dirBase, files) == -1)
	{
		std::cerr << "Directory not found: " << dirBase << std::endl;
		unlock();
		return asynError;
	}

	//search files
	status |= getStringParam(P_Search, INPUT_WAVEFORM_LIM, search);

	status |= getIntegerParam(P_CaseSensitive, &caseSense);

	if (caseSense == 0)
	{
		status |= filterList(files, std::string("(?i)").append(search));
	} else {
		status |= filterList(files, search);
	}
	
	if (m_fullPath)
	{
	    std::string dir_prefix = std::string(dirBase) + "/";
	    std::replace(dir_prefix.begin(), dir_prefix.end(), '\\', '/');
		for(std::list<std::string>::iterator it = files.begin(); it != files.end(); ++it)
		{
		    it->insert(0, dir_prefix);
		}
	}
	
	//add appropriate files to PV
	std::string tOut = json_list_to_array(files);
	status |= compressString(tOut, out);

	if (out.size() < OUT_CHAR_LIM)
		std::copy(out.begin(), out.end(), pJSONOut_);
	else
		std::cerr << "File list too long: " << out.size() << std::endl;

	status |= setStringParam(P_JSONOutArr, pJSONOut_);

	/* Do callbacks so higher layers see any changes */
	status |= (asynStatus)callParamCallbacks();

	unlock();

	return (asynStatus)status;
}
Exemple #28
0
 int Component::getIntParam(const std::string& id, const ParameterMap& params)
 {
   return atoi(getStringParam(id, params).c_str());
 }
Exemple #29
0
 double Component::getDoubleParam(const std::string& id, const ParameterMap& params)
 {
   return atof(getStringParam(id, params).c_str());
 }
Exemple #30
0
template<size_t NoOfPZD> bool CLeyboldSimPortDriver::process(asynUser* IOUser, USSPacket<NoOfPZD> const& USSReadPacket, USSPacket<NoOfPZD>& USSWritePacket, size_t TableIndex)
{
	if ((TableIndex < 0) || (TableIndex >= m_RunRecord.size()))
		throw CException(IOUser, asynError, __FUNCTION__, "User / pump not configured");

	RunStates RunState = static_cast<RunStates>(getIntegerParam(TableIndex, RUNNING));
	// Means the running state is in effect or has been requested.
	bool Running = ((RunState == On) || (RunState == Accel));

	//	control bit 10 = 1
	bool RemoteActivated = ((USSReadPacket.m_USSPacketStruct.m_PZD[0] & (1 << 10)) != 0);

	if (RemoteActivated)
	{
		// Running state change can be requested both ways!
		Running = (USSReadPacket.m_USSPacketStruct.m_PZD[0] & (1 << 0));

		// 0 to 1 transition = Error reset Is only run provided if:
		//		the cause for the error has been removed
		//		and control bit 0 = 0 and control bit 10 = 1
		if ((USSReadPacket.m_USSPacketStruct.m_PZD[0] & (1 << 7)) && (RunState==Off))
		{
			// Clear the fault condition.
			setIntegerParam(TableIndex, FAULT, 0);
		}
	}

	{
		epicsGuard < epicsMutex > guard ( CLeyboldSimPortDriver::m_Mutex );

		if ((Running) && (m_RunRecord[TableIndex].m_RunState != On))
		{
			// The running state has just been enabled.
			if (m_RunRecord[TableIndex].m_RunState == Off)
			{
				setIntegerParam(TableIndex, RUNNING, Accel);
				setDoubleParam(TableIndex, MOTORCURRENT, 15.2);
				m_RunRecord[TableIndex].m_RunState = Accel;
				m_RunRecord[TableIndex].m_TimeStamp = getTickCount();
			}
			else
			{
				// Accel.
				// It is intended that the (simulated) pump speed ramps up to full speed in Duration
				static const unsigned Duration = 2000;
				unsigned ElapsedTime = getTickCount() - m_RunRecord[TableIndex].m_TimeStamp;
				setIntegerParam(TableIndex, STATORFREQUENCY, (ElapsedTime * NormalStatorFrequency) / Duration);
				if (ElapsedTime >= Duration)
				{
					setDefaultValues(TableIndex);
					m_RunRecord[TableIndex].m_RunState = On;
					m_RunRecord[TableIndex].m_TimeStamp = getTickCount();
				}
			}
		}
		else if ((!Running) && (m_RunRecord[TableIndex].m_RunState != Off))
		{
			// The running state has just been disabled.
			if (m_RunRecord[TableIndex].m_RunState == On)
			{
				setIntegerParam(TableIndex, RUNNING, Decel);
				m_RunRecord[TableIndex].m_RunState = Decel;
				m_RunRecord[TableIndex].m_TimeStamp = getTickCount();
			}
			else if (m_RunRecord[TableIndex].m_RunState == Decel)
			{
				// It is intended that the (simulated) pump speed ramps down to nothing in Duration
				static const int Duration = 2000;
				int ElapsedTime = getTickCount() - m_RunRecord[TableIndex].m_TimeStamp;
				int StatorFrequency = ((Duration - ElapsedTime) * NormalStatorFrequency) / Duration;
				if (StatorFrequency < 3)
					StatorFrequency = 3;
				setIntegerParam(TableIndex, STATORFREQUENCY, StatorFrequency);
				if (ElapsedTime >= Duration)
				{
					setIntegerParam(TableIndex, RUNNING, Moving);
					m_RunRecord[TableIndex].m_RunState = Moving;
					m_RunRecord[TableIndex].m_TimeStamp = getTickCount();
				}
			}
			else if (m_RunRecord[TableIndex].m_RunState == Moving)
			{
				// It is intended that the pump remains in the 'Moving' state for another Duration
				static const unsigned Duration = 2000;
				unsigned ElapsedTime = getTickCount() - m_RunRecord[TableIndex].m_TimeStamp;
				if (ElapsedTime >= Duration)
				{
					setIntegerParam(TableIndex, STATORFREQUENCY, 0);
					setIntegerParam(TableIndex, RUNNING, Off);
					m_RunRecord[TableIndex].m_RunState = Off;
					m_RunRecord[TableIndex].m_TimeStamp = getTickCount();
				}
			}
		}
	}

	USSWritePacket.m_USSPacketStruct.m_PZD[0] = 0;
	RunState = m_RunRecord[TableIndex].m_RunState;
	if (RunState == On)
		USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 10);
	else if (RunState == Accel)
		USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 4);
	else if (RunState == Decel)
		USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 5);
	else if (RunState == Moving)
		USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 11);

	// Remote has been activated 1 = start/stop (control bit 0) and reset(control bit 7) through serial interface is possible.
	USSWritePacket.m_USSPacketStruct.m_PZD[0] |= ((RemoteActivated ? 1 : 0) << 15);

	bool Fault = (getIntegerParam(TableIndex, FAULT) != 0);
	if (Fault)
	{
		// A fault condition causes the controller to stop the pump.
		USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 3);
		setIntegerParam(TableIndex, STATORFREQUENCY, 0);
		setIntegerParam(TableIndex, RUNNING, Off);
		m_RunRecord[TableIndex].m_RunState = Off;
	}
	if (getIntegerParam(TableIndex, WARNINGTEMPERATURE) != 0)
		USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 7);
	if (getIntegerParam(TableIndex, WARNINGHIGHLOAD) != 0)
		USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 13);
	if (getIntegerParam(TableIndex, WARNINGPURGE) != 0)
		USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 14);

	// Frequency - actual value. This is equivalent to parameter 3. Both packet types have this field.
	USSWritePacket.m_USSPacketStruct.m_PZD[1] = getIntegerParam(TableIndex, STATORFREQUENCY);

	epicsUInt16 PKE = 0;
	if (USSReadPacket.m_USSPacketStruct.m_PKE & (1 << 12))
		// The requested parameter is in the least 12 bits.
		PKE = USSReadPacket.m_USSPacketStruct.m_PKE & 0X0FFF;

	switch (PKE)
	{
	case 3 : 
		// Frequency - actual value. This is equivalent to PZD[1].
		USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, STATORFREQUENCY);
		break;
	case 11:
		// Converter temperature - actual value. This is equivalent to PZD[2].
		USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, CONVERTERTEMPERATURE);
		break;
	case 5 :
		// Motor current - actual value. This is equivalent to PZD[3].
		USSWritePacket.m_USSPacketStruct.m_PWE = epicsUInt32(10.0 * getDoubleParam(TableIndex, MOTORCURRENT) + 0.5);
		break;
	case 7 :
		// Motor temperature - actual value. This is equivalent to PZD[4].
		USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, PUMPTEMPERATURE);
		break;
	case 4 :
		// Intermediate circuit voltage Uzk. This is equivalent to PZD[5].
		USSWritePacket.m_USSPacketStruct.m_PWE = epicsUInt32(10.0 * getDoubleParam(TableIndex, CIRCUITVOLTAGE) + 0.5);
		break;
	case 2 : 
		// Software version (I assume this means firmware). e.g. 3.03.05
		char CBuf[8]; // 7 chars plus null termination.
		int Major, Minor1, Minor2;
		getStringParam(TableIndex, FIRMWAREVERSION, sizeof(CBuf), CBuf);
		sscanf(CBuf, "%1d.%02d.%02d", &Major, &Minor1, &Minor2);
		USSWritePacket.m_USSPacketStruct.m_PWE = Major * 10000 + Minor1 * 100 + Minor2;
		break;
	case 171:
		// Error code
		USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, FAULT);
		break;
	case 227:
		// Temperature Warning code
		USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, WARNINGTEMPERATURE);
		break;
	case 228:
		// Load warning code.
		USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, WARNINGHIGHLOAD);
		break;
	case 230:
		// Purge warning code.
		USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, WARNINGPURGE);
		break;

	default:
		break;
		// No action.
	}

	USSWritePacket.GenerateChecksum();
	USSWritePacket.m_USSPacketStruct.HToN();

	size_t nbytesOut;
	asynStatus status = pasynOctetSyncIO->write(IOUser,
		reinterpret_cast<char*>(&USSWritePacket.m_Bytes), USSPacketStruct<NoOfPZD>::USSPacketSize,
		-1, &nbytesOut);
	if (status == asynDisconnected)
		return false;
	if (status != asynSuccess)
		throw CException(IOUser, status, __FUNCTION__, "Can't write/read:");

	callParamCallbacks(int(TableIndex));
	asynPrint(IOUser, ASYN_TRACE_FLOW, "Packet success %s %s\n", __FILE__, __FUNCTION__);

	return true;

}