#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "pvutils.cpp" #include #include 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(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(fieldField); size_t count = fromString(pv, from, fromStartIndex); processed += count; fromStartIndex += count; } else if(type==scalarArray) { PVScalarArrayPtr pv = static_pointer_cast(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(fieldField); getConvert()->fromString(pv, from[fromStartIndex++]); processed++; } else if(type==structureArray) { PVStructureArrayPtr pv = static_pointer_cast(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] ...\n\n" " -h: Help: Print this message\n" "options:\n" " -r : Request, specifies what fields to return and options, default is '%s'\n" " -w : 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 : Use as an alternate output field separator\n" " -f : Use 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(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 counter; std::tr1::shared_ptr setp; epics::pvData::Mutex mutex; }; class ChannelPutRequesterImpl : public ChannelPutRequester { private: PVStructure::shared_pointer m_pvStructure; BitSet::shared_pointer m_bitSet; Mutex m_pointerMutex; Mutex m_eventMutex; auto_ptr 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::Structure::const_shared_pointer const & /*structure*/) { if (status.isSuccess()) { // show warning if (!status.isOK()) { std::cerr << "[" << m_channelName << "] channel put create: " << status << std::endl; } // 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, 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 get: " << status << std::endl; } m_done.set(); { Lock lock(m_pointerMutex); m_pvStructure = pvStructure; m_bitSet = bitSet; } } else { std::cerr << "[" << m_channelName << "] failed to get: " << status << std::endl; } m_event->signal(); } virtual void putDone(const epics::pvData::Status& status, ChannelPut::shared_pointer const & /*channelPut*/) { 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; } BitSet::shared_pointer getBitSet() { Lock lock(m_pointerMutex); return m_bitSet; } 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] ... * * 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("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 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 = getChannelProviderRegistry()->getProvider("pva"); //epics::pvAccess::ca::CAClientFactory::start(); //ChannelProvider::shared_pointer provider = getChannelProviderRegistry()->getProvider("ca"); bool allOK = true; try { do { // first connect shared_ptr channelRequesterImpl(new ChannelRequesterImpl(quiet)); Channel::shared_pointer channel = provider->createChannel(pvName, channelRequesterImpl); if (channelRequesterImpl->waitUntilConnected(timeOut)) { shared_ptr 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(); // note on bitSet: we get all, we set all channelPut->put(putRequesterImpl->getStructure(), putRequesterImpl->getBitSet()); 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; }