Moved pvget/pvput/pvinfo/eget programs into pvtoolsSrc

These programs are intended for users, they are not tests.
This commit is contained in:
Andrew Johnson
2014-04-22 10:38:17 -05:00
parent 266c883131
commit 6402e2ca1b
9 changed files with 27 additions and 17 deletions

View File

@@ -56,27 +56,10 @@ testCodec_SRCS = testCodec
testCodec_LIBS += pvAccess pvData pvMB Com
TESTS += testCodec
PROD_HOST += pvget
pvget_SRCS += pvget.cpp
pvget_LIBS += pvAccess pvData pvMB Com
PROD_HOST += pvput
pvput_SRCS += pvput.cpp
pvput_LIBS += pvAccess pvData pvMB Com
PROD_HOST += pvinfo
pvinfo_SRCS += pvinfo.cpp
pvinfo_LIBS += pvAccess pvData pvMB Com
PROD_HOST += testGetPerformance
testGetPerformance_SRCS += testGetPerformance.cpp
testGetPerformance_LIBS += pvAccess pvData pvMB Com
PROD_HOST += eget
eget_SRCS += eget.cpp
eget_LIBS += pvAccess pvData pvMB ca Com
PROD_HOST += rpcServiceExample
rpcServiceExample_SRCS += rpcServiceExample.cpp
rpcServiceExample_LIBS += pvAccess pvData pvMB Com

File diff suppressed because it is too large Load Diff

View File

@@ -1,587 +0,0 @@
#include <iostream>
#include <pv/clientFactory.h>
#include <pv/pvAccess.h>
#include <stdio.h>
#include <epicsStdlib.h>
#include <epicsGetopt.h>
#include <epicsThread.h>
#include <pv/logger.h>
#include <pv/lock.h>
#include <vector>
#include <string>
#include <istream>
#include <fstream>
#include <sstream>
#include <pv/event.h>
#include <epicsExit.h>
#include "pvutils.cpp"
#include <pv/caProvider.h>
using namespace std;
using namespace std::tr1;
using namespace epics::pvData;
using namespace epics::pvAccess;
#define DEFAULT_TIMEOUT 3.0
#define DEFAULT_REQUEST "field(value)"
double timeOut = DEFAULT_TIMEOUT;
string request(DEFAULT_REQUEST);
enum PrintMode { ValueOnlyMode, StructureMode, TerseMode };
PrintMode mode = ValueOnlyMode;
char fieldSeparator = ' ';
void usage (void)
{
fprintf (stderr, "\nUsage: pvget [options] <PV name>...\n\n"
" -h: Help: Print this message\n"
"options:\n"
" -r <pv request>: Request, specifies what fields to return and options, default is '%s'\n"
" -w <sec>: Wait time, specifies timeout, default is %f second(s)\n"
" -t: Terse mode - print only value, without names\n"
" -m: Monitor mode\n"
" -q: Quiet mode, print only error messages\n"
" -d: Enable debug output\n"
" -F <ofs>: Use <ofs> as an alternate output field separator\n"
" -f <input file>: Use <input file> as an input that provides a list PV name(s) to be read, use '-' for stdin\n"
" -c: Wait for clean shutdown and report used instance count (for expert users)\n"
"\nexample: pvget double01\n\n"
, DEFAULT_REQUEST, DEFAULT_TIMEOUT);
}
void printValue(String const & channelName, PVStructure::shared_pointer const & pv)
{
if (mode == ValueOnlyMode)
{
PVField::shared_pointer value = pv->getSubField("value");
if (value.get() == 0)
{
std::cerr << "no 'value' field" << std::endl;
std::cout << channelName << std::endl << *(pv.get()) << std::endl << std::endl;
}
else
{
Type valueType = value->getField()->getType();
if (valueType != scalar && valueType != scalarArray)
{
// switch to structure mode
std::cout << channelName << std::endl << *(pv.get()) << std::endl << std::endl;
}
else
{
if (fieldSeparator == ' ' && value->getField()->getType() == scalar)
std::cout << std::setw(30) << std::left << channelName;
else
std::cout << channelName;
std::cout << fieldSeparator;
terse(std::cout, value) << std::endl;
}
}
}
else if (mode == TerseMode)
terseStructure(std::cout, pv) << std::endl;
else
std::cout << channelName << std::endl << *(pv.get()) << std::endl << std::endl;
}
class ChannelGetRequesterImpl : public ChannelGetRequester
{
private:
ChannelGet::shared_pointer m_channelGet;
PVStructure::shared_pointer m_pvStructure;
BitSet::shared_pointer m_bitSet;
Mutex m_pointerMutex;
Event m_event;
String m_channelName;
bool m_done;
public:
ChannelGetRequesterImpl(String channelName) : m_channelName(channelName), m_done(false) {}
virtual String getRequesterName()
{
return "ChannelGetRequesterImpl";
}
virtual void message(String const & message, MessageType messageType)
{
std::cerr << "[" << getRequesterName() << "] message(" << message << ", " << getMessageTypeName(messageType) << ")" << std::endl;
}
virtual void channelGetConnect(const epics::pvData::Status& status,ChannelGet::shared_pointer const & channelGet,
epics::pvData::PVStructure::shared_pointer const & pvStructure,
epics::pvData::BitSet::shared_pointer const & bitSet)
{
if (status.isSuccess())
{
// show warning
if (!status.isOK())
{
std::cerr << "[" << m_channelName << "] channel get create: " << status << std::endl;
}
// assign smart pointers
{
Lock lock(m_pointerMutex);
m_channelGet = channelGet;
m_pvStructure = pvStructure;
m_bitSet = bitSet;
}
channelGet->get(true);
}
else
{
std::cerr << "[" << m_channelName << "] failed to create channel get: " << status << std::endl;
m_event.signal();
}
}
virtual void getDone(const epics::pvData::Status& status)
{
if (status.isSuccess())
{
// show warning
if (!status.isOK())
{
std::cerr << "[" << m_channelName << "] channel get: " << status << std::endl;
}
// access smart pointers
{
Lock lock(m_pointerMutex);
m_done = true;
/*
{
// needed since we access the data
ScopedLock dataLock(m_channelGet);
printValue(m_channelName, m_pvStructure);
}
*/
// this is OK since callee holds also owns it
m_channelGet.reset();
}
}
else
{
std::cerr << "[" << m_channelName << "] failed to get: " << status << std::endl;
{
Lock lock(m_pointerMutex);
// this is OK since caller holds also owns it
m_channelGet.reset();
}
}
m_event.signal();
}
PVStructure::shared_pointer getPVStructure()
{
Lock lock(m_pointerMutex);
return m_pvStructure;
}
bool waitUntilGet(double timeOut)
{
bool signaled = m_event.wait(timeOut);
if (!signaled)
{
std::cerr << "[" << m_channelName << "] get timeout" << std::endl;
return false;
}
Lock lock(m_pointerMutex);
return m_done;
}
};
class MonitorRequesterImpl : public MonitorRequester
{
private:
String m_channelName;
public:
MonitorRequesterImpl(String channelName) : m_channelName(channelName) {};
virtual String getRequesterName()
{
return "MonitorRequesterImpl";
};
virtual void message(String const & message,MessageType messageType)
{
std::cerr << "[" << getRequesterName() << "] message(" << message << ", " << getMessageTypeName(messageType) << ")" << std::endl;
}
virtual void monitorConnect(const epics::pvData::Status& status, Monitor::shared_pointer const & monitor, StructureConstPtr const & /*structure*/)
{
if (status.isSuccess())
{
/*
String str;
structure->toString(&str);
std::cout << str << std::endl;
*/
Status startStatus = monitor->start();
// show error
// TODO and exit
if (!startStatus.isSuccess())
{
std::cerr << "[" << m_channelName << "] channel monitor start: " << startStatus << std::endl;
}
}
else
{
std::cerr << "monitorConnect(" << status << ")" << std::endl;
}
}
virtual void monitorEvent(Monitor::shared_pointer const & monitor)
{
MonitorElement::shared_pointer element;
while (element = monitor->poll())
{
if (mode == ValueOnlyMode)
{
PVField::shared_pointer value = element->pvStructurePtr->getSubField("value");
if (value.get() == 0)
{
std::cerr << "no 'value' field" << std::endl;
std::cout << m_channelName << std::endl;
std::cout << *(element->pvStructurePtr.get()) << std::endl << std::endl;
}
else
{
Type valueType = value->getField()->getType();
if (valueType != scalar && valueType != scalarArray)
{
// switch to structure mode
std::cout << m_channelName << std::endl;
std::cout << *(element->pvStructurePtr.get()) << std::endl << std::endl;
}
else
{
if (fieldSeparator == ' ' && value->getField()->getType() == scalar)
std::cout << std::setw(30) << std::left << m_channelName;
else
std::cout << m_channelName;
std::cout << fieldSeparator;
terse(std::cout, value) << std::endl;
}
}
}
else if (mode == TerseMode)
{
if (fieldSeparator == ' ')
std::cout << std::setw(30) << std::left << m_channelName;
else
std::cout << m_channelName;
std::cout << fieldSeparator;
terseStructure(std::cout, element->pvStructurePtr) << std::endl;
}
else
{
std::cout << m_channelName << std::endl;
std::cout << *(element->pvStructurePtr.get()) << std::endl << std::endl;
}
monitor->release(element);
}
}
virtual void unlisten(Monitor::shared_pointer const & /*monitor*/)
{
std::cerr << "unlisten" << std::endl;
}
};
/*+**************************************************************************
*
* Function: main
*
* Description: pvget main()
* Evaluate command line options, set up PVA, connect the
* channels, print the data as requested
*
* Arg(s) In: [options] <pv-name>...
*
* Arg(s) Out: none
*
* Return(s): Standard return code (0=success, 1=error)
*
**************************************************************************-*/
int main (int argc, char *argv[])
{
int opt; /* getopt() current option */
bool debug = false;
bool cleanupAndReport = false;
bool monitor = false;
bool quiet = false;
istream* inputStream = 0;
ifstream ifs;
bool fromStream = false;
setvbuf(stdout,NULL,_IOLBF,BUFSIZ); /* Set stdout to line buffering */
while ((opt = getopt(argc, argv, ":hr:w:tmqdcF:f:")) != -1) {
switch (opt) {
case 'h': /* Print usage */
usage();
return 0;
case 'w': /* Set PVA timeout value */
if(epicsScanDouble(optarg, &timeOut) != 1 || timeOut <= 0.0)
{
fprintf(stderr, "'%s' is not a valid timeout value "
"- ignored. ('pvget -h' for help.)\n", optarg);
timeOut = DEFAULT_TIMEOUT;
}
break;
case 'r': /* Set PVA timeout value */
request = optarg;
// do not override terse mode
if (mode == ValueOnlyMode) mode = StructureMode;
break;
case 't': /* Terse mode */
mode = TerseMode;
break;
case 'm': /* Monitor mode */
monitor = true;
break;
case 'q': /* Quiet mode */
quiet = true;
break;
case 'd': /* Debug log level */
debug = true;
break;
case 'c': /* Clean-up and report used instance count */
cleanupAndReport = true;
break;
case 'F': /* Store this for output formatting */
fieldSeparator = (char) *optarg;
break;
case 'f': /* Use input stream as input */
{
string fileName = optarg;
if (fileName == "-")
inputStream = &cin;
else
{
ifs.open(fileName.c_str(), ifstream::in);
if (!ifs)
{
fprintf(stderr,
"Failed to open file '%s'.\n",
fileName.c_str());
return 1;
}
else
inputStream = &ifs;
}
fromStream = true;
break;
}
case '?':
fprintf(stderr,
"Unrecognized option: '-%c'. ('pvget -h' for help.)\n",
optopt);
return 1;
case ':':
fprintf(stderr,
"Option '-%c' requires an argument. ('pvget -h' for help.)\n",
optopt);
return 1;
default :
usage();
return 1;
}
}
int nPvs = argc - optind; /* Remaining arg list are PV names */
if (nPvs > 0)
{
// do not allow reading file and command line specified pvs
fromStream = false;
}
else if (nPvs < 1 && !fromStream)
{
fprintf(stderr, "No pv name(s) specified. ('pvget -h' for help.)\n");
return 1;
}
vector<string> pvs; /* Array of PV structures */
if (fromStream)
{
string cn;
while (true)
{
*inputStream >> cn;
if (!(*inputStream))
break;
pvs.push_back(cn);
}
// set nPvs
nPvs = pvs.size();
}
else
{
// copy PV names from command line
for (int n = 0; optind < argc; n++, optind++)
pvs.push_back(argv[optind]);
}
SET_LOG_LEVEL(debug ? logLevelDebug : logLevelError);
std::cout << std::boolalpha;
terseSeparator(fieldSeparator);
bool allOK = true;
{
Requester::shared_pointer requester(new RequesterImpl("pvget"));
PVStructure::shared_pointer pvRequest = CreateRequest::create()->createRequest(request);
if(pvRequest.get()==NULL) {
fprintf(stderr, "failed to parse request string\n");
return 1;
}
ClientFactory::start();
ChannelProvider::shared_pointer provider = getChannelAccess()->getProvider("pva");
//epics::pvAccess::ca::CAClientFactory::start();
//ChannelProvider::shared_pointer provider = getChannelAccess()->getProvider("ca");
// first connect to all, this allows resource (e.g. TCP connection) sharing
vector<Channel::shared_pointer> channels(nPvs);
for (int n = 0; n < nPvs; n++)
{
shared_ptr<ChannelRequesterImpl> channelRequesterImpl(new ChannelRequesterImpl(quiet));
channels[n] = provider->createChannel(pvs[n], channelRequesterImpl);
}
// for now a simple iterating sync implementation, guarantees order
for (int n = 0; n < nPvs; n++)
{
/*
shared_ptr<ChannelRequesterImpl> channelRequesterImpl(new ChannelRequesterImpl());
Channel::shared_pointer channel = provider->createChannel(pvs[n], channelRequesterImpl);
*/
Channel::shared_pointer channel = channels[n];
shared_ptr<ChannelRequesterImpl> channelRequesterImpl = dynamic_pointer_cast<ChannelRequesterImpl>(channel->getChannelRequester());
if (channelRequesterImpl->waitUntilConnected(timeOut))
{
shared_ptr<GetFieldRequesterImpl> getFieldRequesterImpl;
// probe for value field
if (mode == ValueOnlyMode)
{
getFieldRequesterImpl.reset(new GetFieldRequesterImpl(channel));
// get all to be immune to bad clients not supporting selective getField request
channel->getField(getFieldRequesterImpl, "");
}
if (getFieldRequesterImpl.get() == 0 ||
getFieldRequesterImpl->waitUntilFieldGet(timeOut))
{
// check probe
if (getFieldRequesterImpl.get())
{
Structure::const_shared_pointer structure =
dynamic_pointer_cast<const Structure>(getFieldRequesterImpl->getField());
if (structure.get() == 0 || structure->getField("value").get() == 0)
{
// fallback to structure
mode = StructureMode;
pvRequest = CreateRequest::create()->createRequest("field()");
}
}
if (!monitor)
{
shared_ptr<ChannelGetRequesterImpl> getRequesterImpl(new ChannelGetRequesterImpl(channel->getChannelName()));
ChannelGet::shared_pointer channelGet = channel->createChannelGet(getRequesterImpl, pvRequest);
allOK &= getRequesterImpl->waitUntilGet(timeOut);
if (allOK)
printValue(channel->getChannelName(), getRequesterImpl->getPVStructure());
}
else
{
shared_ptr<MonitorRequesterImpl> monitorRequesterImpl(new MonitorRequesterImpl(channel->getChannelName()));
Monitor::shared_pointer monitorGet = channel->createMonitor(monitorRequesterImpl, pvRequest);
allOK &= true;
}
}
else
{
allOK = false;
channel->destroy();
std::cerr << "[" << channel->getChannelName() << "] failed to get channel introspection data" << std::endl;
}
}
else
{
allOK = false;
channel->destroy();
std::cerr << "[" << channel->getChannelName() << "] connection timeout" << std::endl;
}
}
if (allOK && monitor)
{
while (true)
epicsThreadSleep(timeOut);
}
ClientFactory::stop();
}
if (cleanupAndReport)
{
// TODO implement wait on context
epicsThreadSleep ( 3.0 );
//std::cout << "-----------------------------------------------------------------------" << std::endl;
//epicsExitCallAtExits();
}
return allOK ? 0 : 1;
}

View File

@@ -1,190 +0,0 @@
#include <iostream>
#include <pv/clientFactory.h>
#include <pv/pvAccess.h>
#include <stdio.h>
#include <epicsStdlib.h>
#include <epicsGetopt.h>
#include <epicsThread.h>
#include <pv/logger.h>
#include <pv/lock.h>
#include <vector>
#include <string>
#include <sstream>
#include <pv/event.h>
#include <epicsExit.h>
#include "pvutils.cpp"
using namespace std;
using namespace std::tr1;
using namespace epics::pvData;
using namespace epics::pvAccess;
#define DEFAULT_TIMEOUT 3.0
double timeOut = DEFAULT_TIMEOUT;
void usage (void)
{
fprintf (stderr, "\nUsage: pvinfo [options] <PV name>...\n\n"
" -h: Help: Print this message\n"
"options:\n"
" -w <sec>: Wait time, specifies timeout, default is %f second(s)\n"
" -d: Enable debug output\n"
" -c: Wait for clean shutdown and report used instance count (for expert users)"
"\nExample: pvinfo double01\n\n"
, DEFAULT_TIMEOUT);
}
/*+**************************************************************************
*
* Function: main
*
* Description: pvinfo main()
* Evaluate command line options, set up PVA, connect the
* channels, print the data as requested
*
* Arg(s) In: [options] <pv-name>...
*
* Arg(s) Out: none
*
* Return(s): Standard return code (0=success, 1=error)
*
**************************************************************************-*/
int main (int argc, char *argv[])
{
int opt; /* getopt() current option */
bool debug = false;
bool cleanupAndReport = false;
setvbuf(stdout,NULL,_IOLBF,BUFSIZ); /* Set stdout to line buffering */
while ((opt = getopt(argc, argv, ":hw:dc")) != -1) {
switch (opt) {
case 'h': /* Print usage */
usage();
return 0;
case 'w': /* Set PVA timeout value */
if(epicsScanDouble(optarg, &timeOut) != 1 || timeOut <= 0.0)
{
fprintf(stderr, "'%s' is not a valid timeout value "
"- ignored. ('pvget -h' for help.)\n", optarg);
timeOut = DEFAULT_TIMEOUT;
}
break;
case 'd': /* Debug log level */
debug = true;
break;
case 'c': /* Clean-up and report used instance count */
cleanupAndReport = true;
break;
case '?':
fprintf(stderr,
"Unrecognized option: '-%c'. ('pvinfo -h' for help.)\n",
optopt);
return 1;
case ':':
fprintf(stderr,
"Option '-%c' requires an argument. ('pvinfo -h' for help.)\n",
optopt);
return 1;
default :
usage();
return 1;
}
}
int nPvs = argc - optind; /* Remaining arg list are PV names */
if (nPvs < 1)
{
fprintf(stderr, "No pv name(s) specified. ('pvinfo -h' for help.)\n");
return 1;
}
vector<string> pvs; /* Array of PV names */
for (int n = 0; optind < argc; n++, optind++)
pvs.push_back(argv[optind]); /* Copy PV names from command line */
SET_LOG_LEVEL(debug ? logLevelDebug : logLevelError);
std::cout << std::boolalpha;
bool allOK = true;
{
Requester::shared_pointer requester(new RequesterImpl("pvinfo"));
ClientFactory::start();
ChannelProvider::shared_pointer provider = getChannelAccess()->getProvider("pva");
// first connect to all, this allows resource (e.g. TCP connection) sharing
vector<Channel::shared_pointer> channels(nPvs);
for (int n = 0; n < nPvs; n++)
{
shared_ptr<ChannelRequesterImpl> channelRequesterImpl(new ChannelRequesterImpl());
channels[n] = provider->createChannel(pvs[n], channelRequesterImpl);
}
// for now a simple iterating sync implementation, guarantees order
for (int n = 0; n < nPvs; n++)
{
Channel::shared_pointer channel = channels[n];
shared_ptr<ChannelRequesterImpl> channelRequesterImpl = dynamic_pointer_cast<ChannelRequesterImpl>(channel->getChannelRequester());
if (channelRequesterImpl->waitUntilConnected(timeOut))
{
shared_ptr<GetFieldRequesterImpl> getFieldRequesterImpl(new GetFieldRequesterImpl(channel));
channel->getField(getFieldRequesterImpl, "");
if (getFieldRequesterImpl->waitUntilFieldGet(timeOut))
{
Structure::const_shared_pointer structure =
dynamic_pointer_cast<const Structure>(getFieldRequesterImpl->getField());
channel->printInfo();
if (structure)
{
String s;
structure->toString(&s);
std::cout << s << std::endl << std::endl;
}
else
{
std::cout << "(null introspection data)" << std::endl << std::endl;
}
}
else
{
allOK = false;
channel->destroy();
std::cerr << "[" << channel->getChannelName() << "] failed to get channel introspection data" << std::endl;
}
}
else
{
allOK = false;
channel->destroy();
std::cerr << "[" << channel->getChannelName() << "] connection timeout" << std::endl;
}
}
ClientFactory::stop();
}
if (cleanupAndReport)
{
// TODO implement wait on context
epicsThreadSleep ( 3.0 );
//std::cout << "-----------------------------------------------------------------------" << std::endl;
//epicsExitCallAtExits();
}
return allOK ? 0 : 1;
}

View File

@@ -1,628 +0,0 @@
#include <iostream>
#include <pv/clientFactory.h>
#include <pv/pvAccess.h>
#include <stdio.h>
#include <epicsStdlib.h>
#include <epicsGetopt.h>
#include <epicsThread.h>
#include <pv/logger.h>
#include <pv/lock.h>
#include <vector>
#include <string>
#include <istream>
#include <fstream>
#include <sstream>
#include <pv/event.h>
#include <epicsExit.h>
#include "pvutils.cpp"
#include <pv/convert.h>
#include <pv/caProvider.h>
using namespace std;
using namespace std::tr1;
using namespace epics::pvData;
using namespace epics::pvAccess;
size_t fromString(PVScalarArrayPtr const &pv, StringArray const & from, size_t fromStartIndex = 0)
{
int processed = 0;
size_t fromValueCount = from.size();
// first get count
if (fromStartIndex >= fromValueCount)
throw std::runtime_error("not enough of values");
size_t count;
istringstream iss(from[fromStartIndex]);
iss >> count;
// not fail and entire value is parsed (e.g. to detect 1.2 parsing to 1)
if (iss.fail() || !iss.eof())
throw runtime_error("failed to parse element count value (uint) of field '" + pv->getFieldName() + "' from string value '" + from[fromStartIndex] + "'");
fromStartIndex++;
processed++;
if ((fromStartIndex+count) > fromValueCount)
{
throw runtime_error("not enough array values for field " + pv->getFieldName());
}
PVStringArray::svector valueList(count);
std::copy(from.begin() + fromStartIndex, from.begin() + fromStartIndex + count, valueList.begin());
processed += count;
pv->putFrom<String>(freeze(valueList));
return processed;
}
size_t fromString(PVStructurePtr const & pvStructure, StringArray const & from, size_t fromStartIndex);
size_t fromString(PVStructureArrayPtr const &pv, StringArray const & from, size_t fromStartIndex = 0)
{
int processed = 0;
size_t fromValueCount = from.size();
// first get count
if (fromStartIndex >= fromValueCount)
throw std::runtime_error("not enough of values");
size_t numberOfStructures;
istringstream iss(from[fromStartIndex]);
iss >> numberOfStructures;
// not fail and entire value is parsed (e.g. to detect 1.2 parsing to 1)
if (iss.fail() || !iss.eof())
throw runtime_error("failed to parse element count value (uint) of field '" + pv->getFieldName() + "' from string value '" + from[fromStartIndex] + "'");
fromStartIndex++;
processed++;
PVStructureArray::svector pvStructures;
pvStructures.reserve(numberOfStructures);
PVDataCreatePtr pvDataCreate = getPVDataCreate();
for (size_t i = 0; i < numberOfStructures; ++i)
{
PVStructurePtr pvStructure = pvDataCreate->createPVStructure(pv->getStructureArray()->getStructure());
size_t count = fromString(pvStructure, from, fromStartIndex);
processed += count;
fromStartIndex += count;
pvStructures.push_back(pvStructure);
}
pv->replace(freeze(pvStructures));
return processed;
}
size_t fromString(PVStructurePtr const & pvStructure, StringArray const & from, size_t fromStartIndex = 0)
{
size_t processed = 0;
size_t fromValueCount = from.size();
PVFieldPtrArray const & fieldsData = pvStructure->getPVFields();
if (fieldsData.size() != 0) {
size_t length = pvStructure->getStructure()->getNumberFields();
for(size_t i = 0; i < length; i++) {
PVFieldPtr fieldField = fieldsData[i];
try
{
Type type = fieldField->getField()->getType();
// TODO union/unionArray support
if(type==structure) {
PVStructurePtr pv = static_pointer_cast<PVStructure>(fieldField);
size_t count = fromString(pv, from, fromStartIndex);
processed += count;
fromStartIndex += count;
}
else if(type==scalarArray) {
PVScalarArrayPtr pv = static_pointer_cast<PVScalarArray>(fieldField);
size_t count = fromString(pv, from, fromStartIndex);
processed += count;
fromStartIndex += count;
}
else if(type==scalar) {
if (fromStartIndex >= fromValueCount)
throw std::runtime_error("not enough of values");
PVScalarPtr pv = static_pointer_cast<PVScalar>(fieldField);
getConvert()->fromString(pv, from[fromStartIndex++]);
processed++;
}
else if(type==structureArray) {
PVStructureArrayPtr pv = static_pointer_cast<PVStructureArray>(fieldField);
size_t count = fromString(pv, from, fromStartIndex);
processed += count;
fromStartIndex += count;
}
else {
// union/unionArray not supported
String message("fromString unsupported fieldType ");
TypeFunc::toString(&message,type);
throw std::logic_error(message);
}
}
catch (std::exception &ex)
{
std::ostringstream os;
os << "failed to parse '" << fieldField->getField()->getID() << ' ' << fieldField->getFieldName() << "'";
os << ": " << ex.what();
throw std::runtime_error(os.str());
}
}
}
return processed;
}
#define DEFAULT_TIMEOUT 3.0
#define DEFAULT_REQUEST "field(value)"
double timeOut = DEFAULT_TIMEOUT;
string request(DEFAULT_REQUEST);
enum PrintMode { ValueOnlyMode, StructureMode, TerseMode };
PrintMode mode = ValueOnlyMode;
char fieldSeparator = ' ';
void usage (void)
{
fprintf (stderr, "\nUsage: pvput [options] <PV name> <values>...\n\n"
" -h: Help: Print this message\n"
"options:\n"
" -r <pv request>: Request, specifies what fields to return and options, default is '%s'\n"
" -w <sec>: Wait time, specifies timeout, default is %f second(s)\n"
" -t: Terse mode - print only successfully written value, without names\n"
" -q: Quiet mode, print only error messages\n"
" -d: Enable debug output\n"
" -F <ofs>: Use <ofs> as an alternate output field separator\n"
" -f <input file>: Use <input file> as an input that provides a list PV name(s) to be read, use '-' for stdin\n"
"\nexample: pvput double01 1.234\n\n"
, DEFAULT_REQUEST, DEFAULT_TIMEOUT);
}
void printValue(String const & channelName, PVStructure::shared_pointer const & pv)
{
if (mode == ValueOnlyMode)
{
PVField::shared_pointer value = pv->getSubField("value");
if (value.get() == 0)
{
std::cerr << "no 'value' field" << std::endl;
std::cout << std::endl << *(pv.get()) << std::endl << std::endl;
}
else
{
Type valueType = value->getField()->getType();
if (valueType != scalar && valueType != scalarArray)
{
// switch to structure mode
std::cout << channelName << std::endl << *(pv.get()) << std::endl << std::endl;
}
else
{
if (fieldSeparator == ' ' && value->getField()->getType() == scalar)
std::cout << std::setw(30) << std::left << channelName;
else
std::cout << channelName;
std::cout << fieldSeparator;
terse(std::cout, value) << std::endl;
}
}
}
else if (mode == TerseMode)
terseStructure(std::cout, pv) << std::endl;
else
std::cout << std::endl << *(pv.get()) << std::endl << std::endl;
}
struct AtomicBoolean_null_deleter
{
void operator()(void const *) const {}
};
// standard performance on set/clear, use of tr1::shared_ptr lock-free counter for get
// alternative is to use boost::atomic
class AtomicBoolean
{
public:
AtomicBoolean() : counter(static_cast<void*>(0), AtomicBoolean_null_deleter()) {};
void set() { mutex.lock(); setp = counter; mutex.unlock(); }
void clear() { mutex.lock(); setp.reset(); mutex.unlock(); }
bool get() const { return counter.use_count() == 2; }
private:
std::tr1::shared_ptr<void> counter;
std::tr1::shared_ptr<void> setp;
epics::pvData::Mutex mutex;
};
class ChannelPutRequesterImpl : public ChannelPutRequester
{
private:
ChannelPut::shared_pointer m_channelPut;
PVStructure::shared_pointer m_pvStructure;
BitSet::shared_pointer m_bitSet;
Mutex m_pointerMutex;
Mutex m_eventMutex;
auto_ptr<Event> m_event;
String m_channelName;
AtomicBoolean m_done;
public:
ChannelPutRequesterImpl(String channelName) : m_channelName(channelName)
{
resetEvent();
}
virtual String getRequesterName()
{
return "ChannelPutRequesterImpl";
}
virtual void message(String const & message, MessageType messageType)
{
std::cerr << "[" << getRequesterName() << "] message(" << message << ", " << getMessageTypeName(messageType) << ")" << std::endl;
}
virtual void channelPutConnect(const epics::pvData::Status& status,
ChannelPut::shared_pointer const & channelPut,
epics::pvData::PVStructure::shared_pointer const & pvStructure,
epics::pvData::BitSet::shared_pointer const & bitSet)
{
if (status.isSuccess())
{
// show warning
if (!status.isOK())
{
std::cerr << "[" << m_channelName << "] channel put create: " << status << std::endl;
}
// assign smart pointers
{
Lock lock(m_pointerMutex);
m_channelPut = channelPut;
m_pvStructure = pvStructure;
m_bitSet = bitSet;
}
// we always put all
m_bitSet->set(0);
// get immediately old value
channelPut->get();
}
else
{
std::cerr << "[" << m_channelName << "] failed to create channel put: " << status << std::endl;
m_event->signal();
}
}
virtual void getDone(const epics::pvData::Status& status)
{
if (status.isSuccess())
{
// show warning
if (!status.isOK())
{
std::cerr << "[" << m_channelName << "] channel get: " << status << std::endl;
}
m_done.set();
/*
// access smart pointers
// do not print old value in terseMode
if (!m_supressGetValue.get())
{
Lock lock(m_pointerMutex);
{
// needed since we access the data
ScopedLock dataLock(m_channelPut);
printValue(m_channelName, m_pvStructure);
}
}
*/
}
else
{
std::cerr << "[" << m_channelName << "] failed to get: " << status << std::endl;
}
m_event->signal();
}
virtual void putDone(const epics::pvData::Status& status)
{
if (status.isSuccess())
{
// show warning
if (!status.isOK())
{
std::cerr << "[" << m_channelName << "] channel put: " << status << std::endl;
}
m_done.set();
}
else
{
std::cerr << "[" << m_channelName << "] failed to put: " << status << std::endl;
}
m_event->signal();
}
PVStructure::shared_pointer getStructure()
{
Lock lock(m_pointerMutex);
return m_pvStructure;
}
void resetEvent()
{
Lock lock(m_eventMutex);
m_event.reset(new Event());
m_done.clear();
}
bool waitUntilDone(double timeOut)
{
Event* event;
{
Lock lock(m_eventMutex);
event = m_event.get();
}
bool signaled = event->wait(timeOut);
if (!signaled)
{
std::cerr << "[" << m_channelName << "] timeout" << std::endl;
return false;
}
return m_done.get();
}
};
/*+**************************************************************************
*
* Function: main
*
* Description: pvput main()
* Evaluate command line options, set up PVA, connect the
* channels, print the data as requested
*
* Arg(s) In: [options] <pv-name> <values>...
*
* Arg(s) Out: none
*
* Return(s): Standard return code (0=success, 1=error)
*
**************************************************************************-*/
int main (int argc, char *argv[])
{
int opt; /* getopt() current option */
bool debug = false;
bool quiet = false;
istream* inputStream = 0;
ifstream ifs;
bool fromStream = false;
setvbuf(stdout,NULL,_IOLBF,BUFSIZ); /* Set stdout to line buffering */
putenv(const_cast<char*>("POSIXLY_CORRECT=")); /* Behave correct on GNU getopt systems; e.g. handle negative numbers */
while ((opt = getopt(argc, argv, ":hr:w:tqdF:f:")) != -1) {
switch (opt) {
case 'h': /* Print usage */
usage();
return 0;
case 'w': /* Set PVA timeout value */
if(epicsScanDouble(optarg, &timeOut) != 1)
{
fprintf(stderr, "'%s' is not a valid timeout value "
"- ignored. ('pvput -h' for help.)\n", optarg);
timeOut = DEFAULT_TIMEOUT;
}
break;
case 'r': /* Set PVA timeout value */
request = optarg;
// do not override terse mode
if (mode == ValueOnlyMode) mode = StructureMode;
break;
case 't': /* Terse mode */
mode = TerseMode;
break;
case 'd': /* Debug log level */
debug = true;
break;
case 'q': /* Quiet mode */
quiet = true;
break;
case 'F': /* Store this for output formatting */
fieldSeparator = (char) *optarg;
break;
case 'f': /* Use input stream as input */
{
string fileName = optarg;
if (fileName == "-")
inputStream = &cin;
else
{
ifs.open(fileName.c_str(), ifstream::in);
if (!ifs)
{
fprintf(stderr,
"Failed to open file '%s'.\n",
fileName.c_str());
return 1;
}
else
inputStream = &ifs;
}
fromStream = true;
break;
}
case '?':
fprintf(stderr,
"Unrecognized option: '-%c'. ('pvput -h' for help.)\n",
optopt);
return 1;
case ':':
fprintf(stderr,
"Option '-%c' requires an argument. ('pvput -h' for help.)\n",
optopt);
return 1;
default :
usage();
return 1;
}
}
if (argc <= optind)
{
fprintf(stderr, "No pv name specified. ('pvput -h' for help.)\n");
return 1;
}
string pvName = argv[optind++];
int nVals = argc - optind; /* Remaining arg list are PV names */
if (nVals > 0)
{
// do not allow reading file and command line specified pvs
fromStream = false;
}
else if (nVals < 1 && !fromStream)
{
fprintf(stderr, "No value(s) specified. ('pvput -h' for help.)\n");
return 1;
}
vector<string> values;
if (fromStream)
{
string cn;
while (true)
{
*inputStream >> cn;
if (!(*inputStream))
break;
values.push_back(cn);
}
}
else
{
// copy values from command line
for (int n = 0; optind < argc; n++, optind++)
values.push_back(argv[optind]);
}
Requester::shared_pointer requester(new RequesterImpl("pvput"));
PVStructure::shared_pointer pvRequest = CreateRequest::create()->createRequest(request);
if(pvRequest.get()==NULL) {
fprintf(stderr, "failed to parse request string\n");
return 1;
}
SET_LOG_LEVEL(debug ? logLevelDebug : logLevelError);
std::cout << std::boolalpha;
terseSeparator(fieldSeparator);
ClientFactory::start();
ChannelProvider::shared_pointer provider = getChannelAccess()->getProvider("pva");
//epics::pvAccess::ca::CAClientFactory::start();
//ChannelProvider::shared_pointer provider = getChannelAccess()->getProvider("ca");
bool allOK = true;
try
{
do
{
// first connect
shared_ptr<ChannelRequesterImpl> channelRequesterImpl(new ChannelRequesterImpl(quiet));
Channel::shared_pointer channel = provider->createChannel(pvName, channelRequesterImpl);
if (channelRequesterImpl->waitUntilConnected(timeOut))
{
shared_ptr<ChannelPutRequesterImpl> putRequesterImpl(new ChannelPutRequesterImpl(channel->getChannelName()));
if (mode != TerseMode && !quiet)
std::cout << "Old : ";
ChannelPut::shared_pointer channelPut = channel->createChannelPut(putRequesterImpl, pvRequest);
allOK &= putRequesterImpl->waitUntilDone(timeOut);
if (allOK)
{
if (mode != TerseMode && !quiet)
printValue(pvName, putRequesterImpl->getStructure());
// convert value from string
// since we access structure from another thread, we need to lock
{
ScopedLock lock(channelPut);
fromString(putRequesterImpl->getStructure(), values);
}
// we do a put
putRequesterImpl->resetEvent();
channelPut->put(false);
allOK &= putRequesterImpl->waitUntilDone(timeOut);
if (allOK)
{
// and than a get again to verify put
if (mode != TerseMode && !quiet) std::cout << "New : ";
putRequesterImpl->resetEvent();
channelPut->get();
allOK &= putRequesterImpl->waitUntilDone(timeOut);
if (allOK && !quiet)
printValue(pvName, putRequesterImpl->getStructure());
}
}
}
else
{
allOK = false;
channel->destroy();
std::cerr << "[" << channel->getChannelName() << "] connection timeout" << std::endl;
break;
}
}
while (false);
} catch (std::out_of_range& oor) {
allOK = false;
std::cerr << "parse error: not enough of values" << std::endl;
} catch (std::exception& ex) {
allOK = false;
std::cerr << ex.what() << std::endl;
} catch (...) {
allOK = false;
std::cerr << "unknown exception caught" << std::endl;
}
ClientFactory::stop();
return allOK ? 0 : 1;
}

View File

@@ -1,353 +0,0 @@
#include "pvutils.h"
#include <iostream>
#include <string>
#include <ostream>
#include <sstream>
#include <iomanip>
#include <stdexcept>
#include <algorithm>
#include <pv/logger.h>
using namespace std;
using namespace std::tr1;
using namespace epics::pvData;
using namespace epics::pvAccess;
RequesterImpl::RequesterImpl(String const & requesterName) :
m_requesterName(requesterName)
{
}
String RequesterImpl::getRequesterName()
{
return "RequesterImpl";
}
void RequesterImpl::message(String const & message, MessageType messageType)
{
std::cerr << "[" << getRequesterName() << "] message(" << message << ", " << getMessageTypeName(messageType) << ")" << std::endl;
}
std::ostream& operator<<(std::ostream& o, const Status& s)
{
o << '[' << Status::StatusTypeName[s.getType()] << "] ";
String msg = s.getMessage();
if (!msg.empty())
{
o << msg;
}
else
{
o << "(no error message)";
}
// dump stack trace only if on debug mode
if (IS_LOGGABLE(logLevelDebug))
{
String sd = s.getStackDump();
if (!sd.empty())
{
o << std::endl << sd;
}
}
return o;
}
char separator = ' ';
void terseSeparator(char c)
{
separator = c;
}
char arrayCountFlag = true;
void terseArrayCount(bool flag)
{
arrayCountFlag = flag;
}
std::ostream& terse(std::ostream& o, PVField::shared_pointer const & pv)
{
Type type = pv->getField()->getType();
switch (type)
{
case scalar:
o << *(pv.get());
return o;
case structure:
return terseStructure(o, static_pointer_cast<PVStructure>(pv));
break;
case scalarArray:
return terseScalarArray(o, static_pointer_cast<PVScalarArray>(pv));
break;
case structureArray:
return terseStructureArray(o, static_pointer_cast<PVStructureArray>(pv));
break;
default:
throw logic_error("unknown Field type: " + type);
}
}
std::ostream& terseStructure(std::ostream& o, PVStructure::shared_pointer const & pvStructure)
{
PVFieldPtrArray fieldsData = pvStructure->getPVFields();
size_t length = pvStructure->getStructure()->getNumberFields();
bool first = true;
for (size_t i = 0; i < length; i++) {
if (first)
first = false;
else
o << separator;
terse(o, fieldsData[i]);
}
return o;
}
std::ostream& terseScalarArray(std::ostream& o, PVScalarArray::shared_pointer const & pvArray)
{
size_t length = pvArray->getLength();
if (arrayCountFlag)
{
if (length<=0)
{
o << '0';
return o;
}
o << length << separator;
}
bool first = true;
for (size_t i = 0; i < length; i++) {
if (first)
first = false;
else
o << separator;
pvArray->dumpValue(o, i);
}
return o;
// avoid brackets
/*
o << *(pvArray.get());
return o;
*/
}
std::ostream& terseStructureArray(std::ostream& o, PVStructureArray::shared_pointer const & pvArray)
{
size_t length = pvArray->getLength();
if (arrayCountFlag)
{
if (length<=0)
{
o << '0';
return o;
}
o << length << separator;
}
PVStructureArray::const_svector data = pvArray->view();
bool first = true;
for (size_t i = 0; i < length; i++) {
if (first)
first = false;
else
o << separator;
terseStructure(o, data[i]);
}
return o;
}
/* Converts a hex character to its integer value */
char from_hex(char ch) {
return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}
/* Converts an integer value to its hex character*/
char to_hex(char code) {
static char hex[] = "0123456789abcdef";
return hex[code & 15];
}
/* Returns a url-encoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
char *url_encode(const char *str) {
const char *pstr = str;
char *buf = (char*)malloc(strlen(str) * 3 + 1), *pbuf = buf;
bool firstEquals = true;
while (*pstr) {
if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
*pbuf++ = *pstr;
else if (*pstr == ' ')
*pbuf++ = '+';
else if (*pstr == '=' && firstEquals)
{
firstEquals = false;
*pbuf++ = '=';
}
else
*pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
pstr++;
}
*pbuf = '\0';
return buf;
}
ChannelRequesterImpl::ChannelRequesterImpl(bool _printOnlyErrors) :
printOnlyErrors(_printOnlyErrors)
{
}
String ChannelRequesterImpl::getRequesterName()
{
return "ChannelRequesterImpl";
}
void ChannelRequesterImpl::message(String const & message, MessageType messageType)
{
if (!printOnlyErrors || messageType > warningMessage)
std::cerr << "[" << getRequesterName() << "] message(" << message << ", " << getMessageTypeName(messageType) << ")" << std::endl;
}
void ChannelRequesterImpl::channelCreated(const epics::pvData::Status& status, Channel::shared_pointer const & channel)
{
if (status.isSuccess())
{
// show warning
if (!status.isOK())
{
std::cerr << "[" << channel->getChannelName() << "] channel create: " << status << std::endl;
}
}
else
{
std::cerr << "[" << channel->getChannelName() << "] failed to create a channel: " << status << std::endl;
}
}
void ChannelRequesterImpl::channelStateChange(Channel::shared_pointer const & /*channel*/, Channel::ConnectionState connectionState)
{
if (connectionState == Channel::CONNECTED)
{
m_event.signal();
}
/*
else if (connectionState != Channel::DESTROYED)
{
std::cerr << "[" << channel->getChannelName() << "] channel state change: " << Channel::ConnectionStateNames[connectionState] << std::endl;
}
*/
}
bool ChannelRequesterImpl::waitUntilConnected(double timeOut)
{
return m_event.wait(timeOut);
}
GetFieldRequesterImpl::GetFieldRequesterImpl(epics::pvAccess::Channel::shared_pointer channel) :
m_channel(channel)
{
}
String GetFieldRequesterImpl::getRequesterName()
{
return "GetFieldRequesterImpl";
}
void GetFieldRequesterImpl::message(String const & message, MessageType messageType)
{
std::cerr << "[" << getRequesterName() << "] message(" << message << ", " << getMessageTypeName(messageType) << ")" << std::endl;
}
void GetFieldRequesterImpl::getDone(const epics::pvData::Status& status, epics::pvData::FieldConstPtr const & field)
{
if (status.isSuccess())
{
// show warning
if (!status.isOK())
{
std::cerr << "[" << m_channel->getChannelName() << "] getField: " << status << std::endl;
}
// assign smart pointers
{
Lock lock(m_pointerMutex);
m_field = field;
}
}
else
{
// do not complain about missing field
//std::cerr << "[" << m_channel->getChannelName() << "] failed to get channel introspection data: " << status << std::endl;
}
m_event.signal();
}
bool GetFieldRequesterImpl::waitUntilFieldGet(double timeOut)
{
return m_event.wait(timeOut);
}
epics::pvData::FieldConstPtr GetFieldRequesterImpl::getField()
{
Lock lock(m_pointerMutex);
return m_field;
}
// TODO invalid characters check, etc.
bool URI::parse(const string& uri, URI& result)
{
const string prot_end("://");
string::const_iterator prot_i = search(uri.begin(), uri.end(),
prot_end.begin(), prot_end.end());
if( prot_i == uri.end() || prot_i == uri.begin() )
return false;
result.protocol.reserve(distance(uri.begin(), prot_i));
transform(uri.begin(), prot_i,
back_inserter(result.protocol),
::tolower); // protocol is icase
advance(prot_i, prot_end.length());
if ( prot_i == uri.end() )
return false;
string::const_iterator path_i = find(prot_i, uri.end(), '/');
result.host.assign(prot_i, path_i);
string::const_iterator fragment_i = find(path_i, uri.end(), '#');
if ( fragment_i != uri.end() )
result.fragment.assign(fragment_i+1, uri.end());
string::const_iterator query_i = find(path_i, fragment_i, '?');
result.path.assign(path_i, query_i);
result.query_indicated = (query_i != fragment_i);
if ( result.query_indicated )
result.query.assign(++query_i, fragment_i);
return true;
}

View File

@@ -1,93 +0,0 @@
#include <pv/event.h>
#include <pv/pvData.h>
#include <pv/pvAccess.h>
/// terse mode functions
void convertStructure(epics::pvData::StringBuilder buffer, epics::pvData::PVStructure *data, int notFirst);
void convertArray(epics::pvData::StringBuilder buffer, epics::pvData::PVScalarArray * pv, int notFirst);
void convertStructureArray(epics::pvData::StringBuilder buffer, epics::pvData::PVStructureArray * pvdata, int notFirst);
void terseSeparator(char c);
void terseArrayCount(bool flag);
std::ostream& terse(std::ostream& o, epics::pvData::PVField::shared_pointer const & pv);
std::ostream& terseStructure(std::ostream& o, epics::pvData::PVStructure::shared_pointer const & pvStructure);
std::ostream& terseScalarArray(std::ostream& o, epics::pvData::PVScalarArray::shared_pointer const & pvArray);
std::ostream& terseStructureArray(std::ostream& o, epics::pvData::PVStructureArray::shared_pointer const & pvArray);
/* Converts a hex character to its integer value */
char from_hex(char ch);
/* Converts an integer value to its hex character*/
char to_hex(char code);
/* Returns a url-encoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
char *url_encode(const char *str);
#include <string>
struct URI {
public:
static bool parse(const std::string& uri, URI& result);
public:
std::string protocol, host, path, query, fragment;
bool query_indicated;
};
class RequesterImpl :
public epics::pvData::Requester
{
public:
RequesterImpl(epics::pvData::String const & requesterName);
virtual epics::pvData::String getRequesterName();
virtual void message(epics::pvData::String const & message, epics::pvData::MessageType messageType);
private:
epics::pvData::String m_requesterName;
};
class ChannelRequesterImpl :
public epics::pvAccess::ChannelRequester
{
private:
epics::pvData::Event m_event;
bool printOnlyErrors;
public:
ChannelRequesterImpl(bool printOnlyErrors = false);
virtual epics::pvData::String getRequesterName();
virtual void message(epics::pvData::String const & message, epics::pvData::MessageType messageType);
virtual void channelCreated(const epics::pvData::Status& status, epics::pvAccess::Channel::shared_pointer const & channel);
virtual void channelStateChange(epics::pvAccess::Channel::shared_pointer const & channel, epics::pvAccess::Channel::ConnectionState connectionState);
bool waitUntilConnected(double timeOut);
};
class GetFieldRequesterImpl :
public epics::pvAccess::GetFieldRequester
{
private:
epics::pvAccess::Channel::shared_pointer m_channel;
epics::pvData::FieldConstPtr m_field;
epics::pvData::Event m_event;
epics::pvData::Mutex m_pointerMutex;
public:
GetFieldRequesterImpl(epics::pvAccess::Channel::shared_pointer channel);
virtual epics::pvData::String getRequesterName();
virtual void message(epics::pvData::String const & message, epics::pvData::MessageType messageType);
virtual void getDone(const epics::pvData::Status& status, epics::pvData::FieldConstPtr const & field);
epics::pvData::FieldConstPtr getField();
bool waitUntilFieldGet(double timeOut);
};
std::ostream& operator<<(std::ostream& o, const epics::pvData::Status& s);