ChimeraTK-DeviceAccess 03.29.00
Loading...
Searching...
No Matches
NumericAddressedBackend.cc
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Deutsches Elektronen-Synchrotron DESY, MSK, ChimeraTK Project <chimeratk-support@desy.de>
2// SPDX-License-Identifier: LGPL-3.0-or-later
3
5
6#include "async/DomainImpl.h"
8#include "BackendFactory.h"
11#include "Exception.h"
12#include "MapFileParser.h"
13#include "NumericAddress.h"
17#include "parserUtilities.h"
18
19#include <nlohmann/json.hpp>
20
21#include <filesystem>
22
23using json = nlohmann::json;
24
25namespace ChimeraTK {
26
27 /********************************************************************************************************************/
28
30 std::unique_ptr<NumericAddressedRegisterCatalogue> registerMapPointer,
31 const std::string& dataConsistencyKeyDescriptor)
32 : _registerMapPointer(std::move(registerMapPointer)), _registerMap(*_registerMapPointer) {
33 FILL_VIRTUAL_FUNCTION_TEMPLATE_VTABLE(getRegisterAccessor_impl);
34 if(!mapFileName.empty()) {
35 _resolvedMapFileName = resolveMapFileName(mapFileName);
36 MapFileParser parser;
38 }
39 if(!dataConsistencyKeyDescriptor.empty()) {
40 // parse as JSON
41 try {
42 auto jdescr = nlohmann::json::parse(dataConsistencyKeyDescriptor);
43 for(const auto& el : jdescr.items()) {
44 _registerMap.addDataConsistencyRealm(el.key(), el.value());
45 }
46 }
47 catch(json::parse_error& e) {
48 throw ChimeraTK::logic_error(std::format("Parsing DataConsistencyKeys parameter '{}' results in JSON error: {}",
49 dataConsistencyKeyDescriptor, e.what()));
50 }
51 }
52 }
53
54 /********************************************************************************************************************/
55
56 std::string NumericAddressedBackend::resolveMapFileName(const std::string& mapFileName) {
57 // an absolute path is used directly, legacy DMAP entries are already delivered as absolute paths
58 if(mapFileName[0] == '/') {
59 if(std::filesystem::exists(mapFileName)) {
60 return std::filesystem::canonical(mapFileName).string();
61 }
62 throw ChimeraTK::logic_error("Cannot open map file \"" + mapFileName + "\": file not found.");
63 }
64
65 // relative path candidate: relative to the directory of the DMAP file (if a DMAP path is set)
66 std::string dmapFilePath = BackendFactory::getInstance().getDMapFilePath();
67 std::string dmapDir = parserUtilities::extractDirectory(dmapFilePath);
68 std::string candidateA = parserUtilities::concatenatePaths(dmapDir, mapFileName);
69 // a relative DMAP path is itself relative to the cwd; an unset DMAP path yields "./" as directory,
70 // so candidateA collapses to the cwd-relative path, which is the desired fallback anyway
71 if(std::filesystem::exists(candidateA)) {
72 return std::filesystem::canonical(candidateA).string();
73 }
74
75 // fallback candidate: relative to the current working directory
76 std::string candidateB = parserUtilities::convertToAbsolutePath(mapFileName);
77 if(std::filesystem::exists(candidateB)) {
78 return std::filesystem::canonical(candidateB).string();
79 }
80
81 throw ChimeraTK::logic_error("Cannot open map file \"" + mapFileName + "\": file not found.");
82 }
83
84 /********************************************************************************************************************/
85
89
90 /********************************************************************************************************************/
91
92 /* Throw exception if called directly and not implemented by backend */
93 void NumericAddressedBackend::read([[maybe_unused]] uint8_t bar, [[maybe_unused]] uint32_t address,
94 [[maybe_unused]] int32_t* data, [[maybe_unused]] size_t sizeInBytes) {
95 throw ChimeraTK::logic_error("NumericAddressedBackend: internal error: interface read() called w/ 32bit address");
96 }
97
98 /********************************************************************************************************************/
99
100 void NumericAddressedBackend::write([[maybe_unused]] uint8_t bar, [[maybe_unused]] uint32_t address,
101 [[maybe_unused]] int32_t const* data, [[maybe_unused]] size_t sizeInBytes) {
102 throw ChimeraTK::logic_error("NumericAddressedBackend: internal error: interface write() called w/ 32bit address");
103 }
104
105 /********************************************************************************************************************/
106
107 /* Call 32-bit address implementation by default, for backends that don't implement 64-bit */
108 void NumericAddressedBackend::read(uint64_t bar, uint64_t address, int32_t* data, size_t sizeInBytes) {
109#pragma GCC diagnostic push
110#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
111 read(static_cast<uint8_t>(bar), static_cast<uint32_t>(address), data, sizeInBytes);
112#pragma GCC diagnostic pop
113 }
114
115 /********************************************************************************************************************/
116
117 void NumericAddressedBackend::write(uint64_t bar, uint64_t address, int32_t const* data, size_t sizeInBytes) {
118#pragma GCC diagnostic push
119#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
120 write(static_cast<uint8_t>(bar), static_cast<uint32_t>(address), data, sizeInBytes);
121#pragma GCC diagnostic pop
122 }
123
124 /********************************************************************************************************************/
125
126 // Default range of valid BARs
128 return bar <= 5 || bar == 13;
129 }
130
131 /********************************************************************************************************************/
132
133 template<typename UserType>
134 boost::shared_ptr<NDRegisterAccessor<UserType>> NumericAddressedBackend::getRegisterAccessor_impl(
135 const RegisterPath& registerPathName, size_t numberOfWords, size_t wordOffsetInRegister, AccessModeFlags flags) {
137 // get the interrupt information from the map file
138 auto registerInfo = _registerMap.getBackendRegister(registerPathName);
139 if(!registerInfo.getSupportedAccessModes().has(AccessMode::wait_for_new_data)) {
141 "Register " + registerPathName + " does not support AccessMode::wait_for_new_data.");
142 }
143
144 return _asyncDomainsContainer.subscribe<NumericAddressedBackend, std::nullptr_t, UserType>(
145 boost::static_pointer_cast<NumericAddressedBackend>(shared_from_this()),
146 registerInfo.getQualifiedAsyncId().front(), _asyncIsActive, registerPathName, numberOfWords,
147 wordOffsetInRegister, flags);
148 }
149 return getSyncRegisterAccessor<UserType>(registerPathName, numberOfWords, wordOffsetInRegister, flags);
150 }
151
152 /********************************************************************************************************************/
153
154 template<typename UserType>
155 boost::shared_ptr<NDRegisterAccessor<UserType>> NumericAddressedBackend::getSyncRegisterAccessor(
156 const RegisterPath& registerPathName, size_t numberOfWords, size_t wordOffsetInRegister, AccessModeFlags flags) {
157 boost::shared_ptr<NDRegisterAccessor<UserType>> accessor;
158 // obtain register info
159 auto registerInfo = getRegisterInfo(registerPathName);
160 if(registerInfo.doubleBuffer == std::nullopt) {
161 // 1D or scalar register
162 if(registerInfo.getNumberOfDimensions() <= 1) {
163 if(registerInfo.isBitRange) {
164 if(numberOfWords == 0) {
165 numberOfWords = registerInfo.nElements == 0 ? 1 : registerInfo.nElements;
166 }
167 size_t nParentElements = registerInfo.nElements == 0 ? 1 : registerInfo.nElements;
168 if(numberOfWords + wordOffsetInRegister > nParentElements) {
169 throw ChimeraTK::logic_error("Error in '" + registerPathName + "': Requested number of words+offset " +
170 std::to_string(numberOfWords + wordOffsetInRegister) + " exceeds register size of " +
171 std::to_string(nParentElements) + ".");
172 }
173 // Target must point to the full parent register (all elements)
174 uint64_t targetSizeBytes = nParentElements * registerInfo.elementPitchBits / 8;
175 RegisterPath targetRegisterPath = numeric_address::BAR() / std::to_string(registerInfo.bar) /
176 (std::to_string(registerInfo.address) + "*" + std::to_string(targetSizeBytes) + 'u' +
177 std::to_string(registerInfo.elementPitchBits));
178 auto target = getSyncRegisterAccessor<uint64_t>(targetRegisterPath, nParentElements, 0, {});
179
180 if(flags.has(AccessMode::raw)) {
181 return boost::make_shared<detail::BitRangeAccessorDecorator<UserType, true>>(
182 shared_from_this(), targetRegisterPath, target, registerInfo, numberOfWords, wordOffsetInRegister);
183 }
184 return boost::make_shared<detail::BitRangeAccessorDecorator<UserType, false>>(
185 shared_from_this(), targetRegisterPath, target, registerInfo, numberOfWords, wordOffsetInRegister);
186 }
187 if(registerInfo.channels.front().dataType == NumericAddressedRegisterInfo::Type::FIXED_POINT ||
188 registerInfo.channels.front().dataType == NumericAddressedRegisterInfo::Type::VOID ||
189 registerInfo.channels.front().dataType == NumericAddressedRegisterInfo::Type::IEEE754) {
190 if(flags.has(AccessMode::raw)) {
191 accessor = boost::shared_ptr<NDRegisterAccessor<UserType>>(
192 new NumericAddressedBackendRegisterAccessor<UserType, true>(
193 shared_from_this(), registerPathName, numberOfWords, wordOffsetInRegister, flags));
194 }
195 else {
196 accessor = boost::shared_ptr<NDRegisterAccessor<UserType>>(
197 new NumericAddressedBackendRegisterAccessor<UserType, false>(
198 shared_from_this(), registerPathName, numberOfWords, wordOffsetInRegister, flags));
199 }
200 }
201 else if(registerInfo.channels.front().dataType == NumericAddressedRegisterInfo::Type::ASCII) {
202 if constexpr(!std::is_same<UserType, std::string>::value) {
203 throw ChimeraTK::logic_error("NumericAddressedBackend: ASCII data must be read with std::string UserType.");
204 }
205 else {
206 accessor = boost::shared_ptr<NDRegisterAccessor<UserType>>(new NumericAddressedBackendASCIIAccessor(
207 shared_from_this(), registerPathName, numberOfWords, wordOffsetInRegister, flags));
208 }
209 }
210 else {
211 throw ChimeraTK::logic_error("NumericAddressedBackend: trying to get accessor for unsupported data type");
212 }
213 }
214 // 2D multiplexed register
215 else {
216 flags.checkForUnknownFlags({});
217 accessor =
218 boost::shared_ptr<NDRegisterAccessor<UserType>>(new NumericAddressedBackendMuxedRegisterAccessor<UserType>(
219 registerPathName, numberOfWords, wordOffsetInRegister, shared_from_this()));
220 }
221 }
222 // double buffer register
223 else {
224 const auto& enableRegPath = registerInfo.doubleBuffer->enableRegisterPath;
225 auto& controlState = _doubleBufferMutexMap[enableRegPath];
226 if(!controlState) {
227 controlState = std::make_shared<detail::CountedRecursiveMutex>();
228 }
229 accessor = boost::make_shared<DoubleBufferAccessor<UserType>>(*registerInfo.doubleBuffer, shared_from_this(),
230 controlState, registerPathName, numberOfWords, wordOffsetInRegister, flags);
231 }
232 accessor->setExceptionBackend(shared_from_this());
233 return accessor;
234 }
235
236 /********************************************************************************************************************/
237
239 _asyncIsActive = true;
240 // Iterating all async domains must happen under the container lock. We prepare a lambda that is executed via
241 // DomainsContainer::forEach().
242 auto activateDomain = [this](size_t key, boost::shared_ptr<async::Domain>& domain) {
243 auto domainImpl = boost::dynamic_pointer_cast<async::DomainImpl<std::nullptr_t>>(domain);
244 assert(domainImpl);
245 auto subscriptionDone = this->activateSubscription(key, domainImpl);
246 // Wait until the backends reports that the subscription is complete (typically set from inside another thread)
247 // before polling the initial values when activating the async domain. This is necessary to make sure we don't
248 // miss an update that came in after polling the initial value.
249 subscriptionDone.wait();
250 domainImpl->activate(nullptr);
251 };
252
253 _asyncDomainsContainer.forEach(activateDomain);
254 }
255
256 /********************************************************************************************************************/
257
258 // The default implementation just returns a ready future.
259 std::future<void> NumericAddressedBackend::activateSubscription([[maybe_unused]] unsigned int interruptNumber,
260 [[maybe_unused]] boost::shared_ptr<async::DomainImpl<std::nullptr_t>> asyncDomain) {
261 std::promise<void> subscriptionDonePromise;
262 subscriptionDonePromise.set_value();
263 return subscriptionDonePromise.get_future();
264 }
265
266 /********************************************************************************************************************/
267
269 _asyncIsActive = false;
270
271 _asyncDomainsContainer.forEach([](size_t, boost::shared_ptr<async::Domain>& domain) { domain->deactivate(); });
272
273 closeImpl();
274 }
275
276 /********************************************************************************************************************/
277
281
282 /********************************************************************************************************************/
283
287
288 /********************************************************************************************************************/
289
291 _asyncIsActive = false;
292 }
293
294 /********************************************************************************************************************/
295
296} // namespace ChimeraTK
nlohmann::json json
#define FILL_VIRTUAL_FUNCTION_TEMPLATE_VTABLE(functionName)
Fill the vtable of a virtual function template defined with DEFINE_VIRTUAL_FUNCTION_TEMPLATE.
Set of AccessMode flags with additional functionality for an easier handling.
Definition AccessMode.h:48
bool has(AccessMode flag) const
Check if a certain flag is in the set.
Definition AccessMode.cc:20
static BackendFactory & getInstance()
Static function to get an instance of factory.
std::string getDMapFilePath()
Returns the _DMapFilePath.
async::DomainsContainer _asyncDomainsContainer
Container for async::Domains to support wait_for_new_data.
static std::pair< NumericAddressedRegisterCatalogue, MetadataCatalogue > parse(const std::string &fileName)
Performs parsing of specified MAP file, resulting in catalogue objects describing all registers and m...
Container for backend metadata.
MetadataCatalogue _metadataCatalogue
metadata catalogue
RegisterCatalogue getRegisterCatalogue() const override
Return the register catalogue with detailed information on all registers.
virtual bool barIndexValid(uint64_t bar)
Function to be implemented by the backends.
NumericAddressedRegisterCatalogue & _registerMap
NumericAddressedRegisterInfo getRegisterInfo(const RegisterPath &registerPathName)
getRegisterInfo returns a NumericAddressedRegisterInfo object for the given register.
NumericAddressedBackend(const std::string &mapFileName="", std::unique_ptr< NumericAddressedRegisterCatalogue > registerMapPointer=std::make_unique< NumericAddressedRegisterCatalogue >(), const std::string &dataConsistencyKeyDescriptor="")
void setExceptionImpl() noexcept override
Turn off the internal variable which remembers that async is active.
void close() final
Deactivates all asynchronous accessors and calls closeImpl().
MetadataCatalogue getMetadataCatalogue() const override
Return the device metadata catalogue.
void activateAsyncRead() noexcept override
Activate asyncronous read for all transfer elements where AccessMode::wait_for_new_data is set.
std::string _resolvedMapFileName
The resolved absolute path of the map file used for parsing and for any derived naming (e....
virtual void closeImpl()
All backends derrived from NumericAddressedBackend must implement closeImpl() instead of close.
virtual void write(uint64_t bar, uint64_t address, int32_t const *data, size_t sizeInBytes)
Write function to be implemented by backends.
virtual std::future< void > activateSubscription(uint32_t interruptNumber, boost::shared_ptr< async::DomainImpl< std::nullptr_t > > asyncDomain)
Activate/create the subscription for a given interrupt (for instance by starting the according interr...
virtual void read(uint64_t bar, uint64_t address, int32_t *data, size_t sizeInBytes)
Read function to be implemented by backends.
void addDataConsistencyRealm(const RegisterPath &registerPath, const std::string &realmName)
NumericAddressedRegisterInfo getBackendRegister(const RegisterPath &registerPathName) const override
Note: Override this function if backend has "hidden" registers which are not added to the map and hen...
std::unique_ptr< BackendRegisterCatalogueBase > clone() const override
Create deep copy of the catalogue.
Catalogue of register information.
Class to store a register path name.
boost::shared_ptr< AsyncNDRegisterAccessor< UserDataType > > subscribe(boost::shared_ptr< BackendType > backend, size_t domainId, bool activate, RegisterPath name, size_t numberOfWords, size_t wordOffsetInRegister, AccessModeFlags flags)
Get an accessor from a particular domain.
void forEach(const std::function< void(size_t, boost::shared_ptr< Domain > &)> &executeMe)
Iterate all Domains under the container lock.
Exception thrown when a logic error has occured.
Definition Exception.h:51
RegisterPath BAR()
The numeric_address::BAR() function can be used to directly access registers by numeric addresses,...
std::string extractDirectory(std::string const &path)
Returns the path to the directory containing the file provided as the input parameter.
std::string concatenatePaths(const std::string &path1, const std::string &path2)
Concatenates two given paths using custom rules.
std::string convertToAbsolutePath(std::string const &relativePath)
Converts a relative path to its absolute path.
@ wait_for_new_data
Make any read blocking until new data has arrived since the last read.
@ raw
Raw access: disable any possible conversion from the original hardware data type into the given UserT...
STL namespace.
std::string to_string(const std::string &v)