##// END OF EJS Templates
Fix bug in acquisition !. Test fuzzing with 30 var in 8 group
perrinel -
r1398:8cb3639e4927
parent child
Show More
@@ -1,386 +1,368
1 #include "Variable/VariableAcquisitionWorker.h"
1 #include "Variable/VariableAcquisitionWorker.h"
2
2
3 #include "Variable/Variable.h"
3 #include "Variable/Variable.h"
4
4
5 #include <Data/AcquisitionRequest.h>
5 #include <Data/AcquisitionRequest.h>
6 #include <Data/SqpRange.h>
6 #include <Data/SqpRange.h>
7
7
8 #include <unordered_map>
8 #include <unordered_map>
9 #include <utility>
9 #include <utility>
10
10
11 #include <QMutex>
11 #include <QMutex>
12 #include <QReadWriteLock>
12 #include <QReadWriteLock>
13 #include <QThread>
13 #include <QThread>
14
14
15 #include <cmath>
15 #include <cmath>
16
16
17 Q_LOGGING_CATEGORY(LOG_VariableAcquisitionWorker, "VariableAcquisitionWorker")
17 Q_LOGGING_CATEGORY(LOG_VariableAcquisitionWorker, "VariableAcquisitionWorker")
18
18
19 struct VariableAcquisitionWorker::VariableAcquisitionWorkerPrivate {
19 struct VariableAcquisitionWorker::VariableAcquisitionWorkerPrivate {
20
20
21 explicit VariableAcquisitionWorkerPrivate(VariableAcquisitionWorker *parent)
21 explicit VariableAcquisitionWorkerPrivate(VariableAcquisitionWorker *parent)
22 : m_Lock{QReadWriteLock::Recursive}, q{parent}
22 : m_Lock{QReadWriteLock::Recursive}, q{parent}
23 {
23 {
24 }
24 }
25
25
26 void lockRead() { m_Lock.lockForRead(); }
26 void lockRead() { m_Lock.lockForRead(); }
27 void lockWrite() { m_Lock.lockForWrite(); }
27 void lockWrite() { m_Lock.lockForWrite(); }
28 void unlock() { m_Lock.unlock(); }
28 void unlock() { m_Lock.unlock(); }
29
29
30 void removeVariableRequest(QUuid vIdentifier);
30 void removeVariableRequest(QUuid vIdentifier);
31
31
32 /// Remove and/or abort all AcqRequest in link with varRequestId
32 /// Remove and/or abort all AcqRequest in link with varRequestId
33 void cancelVarRequest(QUuid varRequestId);
33 void cancelVarRequest(QUuid varRequestId);
34 void removeAcqRequest(QUuid acqRequestId);
34 void removeAcqRequest(QUuid acqRequestId);
35
35
36 QMutex m_WorkingMutex;
36 QMutex m_WorkingMutex;
37 QReadWriteLock m_Lock;
37 QReadWriteLock m_Lock;
38
38
39 std::map<QUuid, QVector<AcquisitionDataPacket> > m_AcqIdentifierToAcqDataPacketVectorMap;
39 std::map<QUuid, QVector<AcquisitionDataPacket> > m_AcqIdentifierToAcqDataPacketVectorMap;
40 std::map<QUuid, AcquisitionRequest> m_AcqIdentifierToAcqRequestMap;
40 std::map<QUuid, AcquisitionRequest> m_AcqIdentifierToAcqRequestMap;
41 std::map<QUuid, QUuid> m_VIdentifierToCurrrentAcqIdMap;
41 std::map<QUuid, QUuid> m_VIdentifierToCurrrentAcqIdMap;
42 VariableAcquisitionWorker *q;
42 VariableAcquisitionWorker *q;
43 };
43 };
44
44
45
45
46 VariableAcquisitionWorker::VariableAcquisitionWorker(QObject *parent)
46 VariableAcquisitionWorker::VariableAcquisitionWorker(QObject *parent)
47 : QObject{parent}, impl{spimpl::make_unique_impl<VariableAcquisitionWorkerPrivate>(this)}
47 : QObject{parent}, impl{spimpl::make_unique_impl<VariableAcquisitionWorkerPrivate>(this)}
48 {
48 {
49 }
49 }
50
50
51 VariableAcquisitionWorker::~VariableAcquisitionWorker()
51 VariableAcquisitionWorker::~VariableAcquisitionWorker()
52 {
52 {
53 qCInfo(LOG_VariableAcquisitionWorker()) << tr("VariableAcquisitionWorker destruction")
53 qCInfo(LOG_VariableAcquisitionWorker()) << tr("VariableAcquisitionWorker destruction")
54 << QThread::currentThread();
54 << QThread::currentThread();
55 this->waitForFinish();
55 this->waitForFinish();
56 }
56 }
57
57
58
58
59 QUuid VariableAcquisitionWorker::pushVariableRequest(QUuid varRequestId, QUuid vIdentifier,
59 QUuid VariableAcquisitionWorker::pushVariableRequest(QUuid varRequestId, QUuid vIdentifier,
60 DataProviderParameters parameters,
60 DataProviderParameters parameters,
61 std::shared_ptr<IDataProvider> provider)
61 std::shared_ptr<IDataProvider> provider)
62 {
62 {
63 qCDebug(LOG_VariableAcquisitionWorker())
63 qCDebug(LOG_VariableAcquisitionWorker())
64 << tr("TORM VariableAcquisitionWorker::pushVariableRequest varRequestId: ") << varRequestId
64 << tr("TORM VariableAcquisitionWorker::pushVariableRequest varRequestId: ") << varRequestId
65 << "vId: " << vIdentifier;
65 << "vId: " << vIdentifier;
66 auto varRequestIdCanceled = QUuid();
66 auto varRequestIdCanceled = QUuid();
67
67
68 // Request creation
68 // Request creation
69 auto acqRequest = AcquisitionRequest{};
69 auto acqRequest = AcquisitionRequest{};
70 acqRequest.m_VarRequestId = varRequestId;
70 acqRequest.m_VarRequestId = varRequestId;
71 acqRequest.m_vIdentifier = vIdentifier;
71 acqRequest.m_vIdentifier = vIdentifier;
72 acqRequest.m_DataProviderParameters = parameters;
72 acqRequest.m_DataProviderParameters = parameters;
73 acqRequest.m_Size = parameters.m_Times.size();
73 acqRequest.m_Size = parameters.m_Times.size();
74 acqRequest.m_Provider = provider;
74 acqRequest.m_Provider = provider;
75 qCInfo(LOG_VariableAcquisitionWorker()) << tr("Add acqRequest ") << acqRequest.m_AcqIdentifier
75 qCInfo(LOG_VariableAcquisitionWorker()) << tr("Add acqRequest ") << acqRequest.m_AcqIdentifier
76 << acqRequest.m_Size;
76 << acqRequest.m_Size;
77
77
78
78
79 // Register request
79 // Register request
80 impl->lockWrite();
80 impl->lockWrite();
81 impl->m_AcqIdentifierToAcqRequestMap.insert(
81 impl->m_AcqIdentifierToAcqRequestMap.insert(
82 std::make_pair(acqRequest.m_AcqIdentifier, acqRequest));
82 std::make_pair(acqRequest.m_AcqIdentifier, acqRequest));
83
83
84 auto it = impl->m_VIdentifierToCurrrentAcqIdMap.find(vIdentifier);
84 auto it = impl->m_VIdentifierToCurrrentAcqIdMap.find(vIdentifier);
85 if (it != impl->m_VIdentifierToCurrrentAcqIdMap.cend()) {
85 if (it != impl->m_VIdentifierToCurrrentAcqIdMap.cend()) {
86 // A current request already exists, we can cancel it
86 // A current request already exists, we can cancel it
87 // remove old acqIdentifier from the worker
87 // remove old acqIdentifier from the worker
88 auto oldAcqId = it->second;
88 auto oldAcqId = it->second;
89 auto acqIdentifierToAcqRequestMapIt = impl->m_AcqIdentifierToAcqRequestMap.find(oldAcqId);
89 auto acqIdentifierToAcqRequestMapIt = impl->m_AcqIdentifierToAcqRequestMap.find(oldAcqId);
90 if (acqIdentifierToAcqRequestMapIt != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
90 if (acqIdentifierToAcqRequestMapIt != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
91 auto oldAcqRequest = acqIdentifierToAcqRequestMapIt->second;
91 auto oldAcqRequest = acqIdentifierToAcqRequestMapIt->second;
92 varRequestIdCanceled = oldAcqRequest.m_VarRequestId;
92 varRequestIdCanceled = oldAcqRequest.m_VarRequestId;
93 }
93 }
94 impl->unlock();
94 impl->unlock();
95 impl->cancelVarRequest(varRequestIdCanceled);
95 impl->cancelVarRequest(varRequestIdCanceled);
96 }
96 }
97 else {
97 else {
98 impl->unlock();
98 impl->unlock();
99 }
99 }
100
100
101 // Request for the variable, it must be stored and executed
101 // Request for the variable, it must be stored and executed
102 impl->lockWrite();
102 impl->lockWrite();
103 impl->m_VIdentifierToCurrrentAcqIdMap.insert(
103 impl->m_VIdentifierToCurrrentAcqIdMap.insert(
104 std::make_pair(vIdentifier, acqRequest.m_AcqIdentifier));
104 std::make_pair(vIdentifier, acqRequest.m_AcqIdentifier));
105 impl->unlock();
105 impl->unlock();
106
106
107 QMetaObject::invokeMethod(this, "onExecuteRequest", Qt::QueuedConnection,
107 QMetaObject::invokeMethod(this, "onExecuteRequest", Qt::QueuedConnection,
108 Q_ARG(QUuid, acqRequest.m_AcqIdentifier));
108 Q_ARG(QUuid, acqRequest.m_AcqIdentifier));
109
109
110 return varRequestIdCanceled;
110 return varRequestIdCanceled;
111 }
111 }
112
112
113 void VariableAcquisitionWorker::abortProgressRequested(QUuid vIdentifier)
113 void VariableAcquisitionWorker::abortProgressRequested(QUuid vIdentifier)
114 {
114 {
115 impl->lockRead();
115 impl->lockRead();
116
116
117 auto it = impl->m_VIdentifierToCurrrentAcqIdMap.find(vIdentifier);
117 auto it = impl->m_VIdentifierToCurrrentAcqIdMap.find(vIdentifier);
118 if (it != impl->m_VIdentifierToCurrrentAcqIdMap.cend()) {
118 if (it != impl->m_VIdentifierToCurrrentAcqIdMap.cend()) {
119 auto currentAcqId = it->second;
119 auto currentAcqId = it->second;
120
120
121 auto it = impl->m_AcqIdentifierToAcqRequestMap.find(currentAcqId);
121 auto it = impl->m_AcqIdentifierToAcqRequestMap.find(currentAcqId);
122 if (it != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
122 if (it != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
123 auto request = it->second;
123 auto request = it->second;
124 impl->unlock();
124 impl->unlock();
125
125
126 // notify the request aborting to the provider
126 // notify the request aborting to the provider
127 request.m_Provider->requestDataAborting(currentAcqId);
127 request.m_Provider->requestDataAborting(currentAcqId);
128 }
128 }
129 else {
129 else {
130 impl->unlock();
130 impl->unlock();
131 qCWarning(LOG_VariableAcquisitionWorker())
131 qCWarning(LOG_VariableAcquisitionWorker())
132 << tr("Impossible to abort an unknown acquisition request") << currentAcqId;
132 << tr("Impossible to abort an unknown acquisition request") << currentAcqId;
133 }
133 }
134 }
134 }
135 else {
135 else {
136 impl->unlock();
136 impl->unlock();
137 }
137 }
138 }
138 }
139
139
140 void VariableAcquisitionWorker::onVariableRetrieveDataInProgress(QUuid acqIdentifier,
140 void VariableAcquisitionWorker::onVariableRetrieveDataInProgress(QUuid acqIdentifier,
141 double progress)
141 double progress)
142 {
142 {
143 qCInfo(LOG_VariableAcquisitionWorker()) << tr("TORM: onVariableRetrieveDataInProgress ")
143 qCDebug(LOG_VariableAcquisitionWorker()) << tr("TORM: onVariableRetrieveDataInProgress ")
144 << QThread::currentThread()->objectName()
144 << QThread::currentThread()->objectName()
145 << acqIdentifier << progress;
145 << acqIdentifier << progress;
146 impl->lockRead();
146 impl->lockRead();
147 auto aIdToARit = impl->m_AcqIdentifierToAcqRequestMap.find(acqIdentifier);
147 auto aIdToARit = impl->m_AcqIdentifierToAcqRequestMap.find(acqIdentifier);
148 if (aIdToARit != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
148 if (aIdToARit != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
149 auto progressPartSize
149 auto progressPartSize
150 = (aIdToARit->second.m_Size != 0) ? 100 / aIdToARit->second.m_Size : 0;
150 = (aIdToARit->second.m_Size != 0) ? 100 / aIdToARit->second.m_Size : 0;
151
151
152 auto currentPartProgress
152 auto currentPartProgress
153 = std::isnan(progress) ? 0.0 : (progress * progressPartSize) / 100.0;
153 = std::isnan(progress) ? 0.0 : (progress * progressPartSize) / 100.0;
154
154
155 // We can only give an approximation of the currentProgression since its upgrade is async.
155 // We can only give an approximation of the currentProgression since its upgrade is async.
156 qCInfo(LOG_VariableAcquisitionWorker())
157 << tr("Progression: ") << aIdToARit->second.m_Progression << aIdToARit->second.m_Size;
158 auto currentProgression = aIdToARit->second.m_Progression;
156 auto currentProgression = aIdToARit->second.m_Progression;
159 if (currentProgression == aIdToARit->second.m_Size) {
157 if (currentProgression == aIdToARit->second.m_Size) {
160 currentProgression = aIdToARit->second.m_Size - 1;
158 currentProgression = aIdToARit->second.m_Size - 1;
161 }
159 }
162
160
163 auto currentAlreadyProgress = progressPartSize * currentProgression;
161 auto currentAlreadyProgress = progressPartSize * currentProgression;
164
162
165
163
166 auto finalProgression = currentAlreadyProgress + currentPartProgress;
164 auto finalProgression = currentAlreadyProgress + currentPartProgress;
167 emit variableRequestInProgress(aIdToARit->second.m_vIdentifier, finalProgression);
165 emit variableRequestInProgress(aIdToARit->second.m_vIdentifier, finalProgression);
168 qCInfo(LOG_VariableAcquisitionWorker())
169 << tr("TORM: onVariableRetrieveDataInProgress ")
170 << QThread::currentThread()->objectName() << aIdToARit->second.m_vIdentifier
171 << progressPartSize << currentAlreadyProgress << currentPartProgress
172 << finalProgression;
173
166
174 if (finalProgression == 100.0) {
167 if (finalProgression == 100.0) {
175 qCInfo(LOG_VariableAcquisitionWorker())
176 << tr("TORM: onVariableRetrieveDataInProgress : finished : 0.0 ");
177 emit variableRequestInProgress(aIdToARit->second.m_vIdentifier, 0.0);
168 emit variableRequestInProgress(aIdToARit->second.m_vIdentifier, 0.0);
178 }
169 }
179 }
170 }
180 impl->unlock();
171 impl->unlock();
181 }
172 }
182
173
183 void VariableAcquisitionWorker::onVariableAcquisitionFailed(QUuid acqIdentifier)
174 void VariableAcquisitionWorker::onVariableAcquisitionFailed(QUuid acqIdentifier)
184 {
175 {
185 qCDebug(LOG_VariableAcquisitionWorker()) << tr("onVariableAcquisitionFailed")
176 qCDebug(LOG_VariableAcquisitionWorker()) << tr("onVariableAcquisitionFailed")
186 << QThread::currentThread();
177 << QThread::currentThread();
187 impl->lockRead();
178 impl->lockRead();
188 auto it = impl->m_AcqIdentifierToAcqRequestMap.find(acqIdentifier);
179 auto it = impl->m_AcqIdentifierToAcqRequestMap.find(acqIdentifier);
189 if (it != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
180 if (it != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
190 auto request = it->second;
181 auto request = it->second;
191 impl->unlock();
182 impl->unlock();
192 qCDebug(LOG_VariableAcquisitionWorker()) << tr("onVariableAcquisitionFailed")
193 << acqIdentifier << request.m_vIdentifier
194 << QThread::currentThread();
195 emit variableCanceledRequested(request.m_vIdentifier);
183 emit variableCanceledRequested(request.m_vIdentifier);
196 }
184 }
197 else {
185 else {
198 impl->unlock();
186 impl->unlock();
199 // TODO log no acqIdentifier recognized
200 }
187 }
201 }
188 }
202
189
203 void VariableAcquisitionWorker::onVariableDataAcquired(QUuid acqIdentifier,
190 void VariableAcquisitionWorker::onVariableDataAcquired(QUuid acqIdentifier,
204 std::shared_ptr<IDataSeries> dataSeries,
191 std::shared_ptr<IDataSeries> dataSeries,
205 SqpRange dataRangeAcquired)
192 SqpRange dataRangeAcquired)
206 {
193 {
207 qCDebug(LOG_VariableAcquisitionWorker()) << tr("TORM: onVariableDataAcquired on range ")
194 qCDebug(LOG_VariableAcquisitionWorker()) << tr("TORM: onVariableDataAcquired on range ")
208 << acqIdentifier << dataRangeAcquired;
195 << acqIdentifier << dataRangeAcquired;
209 impl->lockWrite();
196 impl->lockWrite();
210 auto aIdToARit = impl->m_AcqIdentifierToAcqRequestMap.find(acqIdentifier);
197 auto aIdToARit = impl->m_AcqIdentifierToAcqRequestMap.find(acqIdentifier);
211 if (aIdToARit != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
198 if (aIdToARit != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
212 // Store the result
199 // Store the result
213 auto dataPacket = AcquisitionDataPacket{};
200 auto dataPacket = AcquisitionDataPacket{};
214 dataPacket.m_Range = dataRangeAcquired;
201 dataPacket.m_Range = dataRangeAcquired;
215 dataPacket.m_DateSeries = dataSeries;
202 dataPacket.m_DateSeries = dataSeries;
216
203
217 auto aIdToADPVit = impl->m_AcqIdentifierToAcqDataPacketVectorMap.find(acqIdentifier);
204 auto aIdToADPVit = impl->m_AcqIdentifierToAcqDataPacketVectorMap.find(acqIdentifier);
218 if (aIdToADPVit != impl->m_AcqIdentifierToAcqDataPacketVectorMap.cend()) {
205 if (aIdToADPVit != impl->m_AcqIdentifierToAcqDataPacketVectorMap.cend()) {
219 // A current request result already exists, we can update it
206 // A current request result already exists, we can update it
220 aIdToADPVit->second.push_back(dataPacket);
207 aIdToADPVit->second.push_back(dataPacket);
221 }
208 }
222 else {
209 else {
223 // First request result for the variable, it must be stored
210 // First request result for the variable, it must be stored
224 impl->m_AcqIdentifierToAcqDataPacketVectorMap.insert(
211 impl->m_AcqIdentifierToAcqDataPacketVectorMap.insert(
225 std::make_pair(acqIdentifier, QVector<AcquisitionDataPacket>() << dataPacket));
212 std::make_pair(acqIdentifier, QVector<AcquisitionDataPacket>() << dataPacket));
226 }
213 }
227
214
228
215
229 // Decrement the counter of the request
216 // Decrement the counter of the request
230 auto &acqRequest = aIdToARit->second;
217 auto &acqRequest = aIdToARit->second;
231 qCInfo(LOG_VariableAcquisitionWorker()) << tr("TORM: +1 update progresson ")
232 << acqIdentifier;
233 acqRequest.m_Progression = acqRequest.m_Progression + 1;
218 acqRequest.m_Progression = acqRequest.m_Progression + 1;
234
219
235 // if the counter is 0, we can return data then run the next request if it exists and
220 // if the counter is 0, we can return data then run the next request if it exists and
236 // removed the finished request
221 // removed the finished request
237 if (acqRequest.m_Size == acqRequest.m_Progression) {
222 if (acqRequest.m_Size == acqRequest.m_Progression) {
238 auto varId = acqRequest.m_vIdentifier;
223 auto varId = acqRequest.m_vIdentifier;
239 // Return the data
224 // Return the data
240 aIdToADPVit = impl->m_AcqIdentifierToAcqDataPacketVectorMap.find(acqIdentifier);
225 aIdToADPVit = impl->m_AcqIdentifierToAcqDataPacketVectorMap.find(acqIdentifier);
241 if (aIdToADPVit != impl->m_AcqIdentifierToAcqDataPacketVectorMap.cend()) {
226 if (aIdToADPVit != impl->m_AcqIdentifierToAcqDataPacketVectorMap.cend()) {
242 emit dataProvided(varId, aIdToADPVit->second);
227 emit dataProvided(varId, aIdToADPVit->second);
243 }
228 }
244 impl->unlock();
229 impl->unlock();
245 }
230 }
246 else {
231 else {
247 impl->unlock();
232 impl->unlock();
248 }
233 }
249 }
234 }
250 else {
235 else {
251 impl->unlock();
236 impl->unlock();
252 qCWarning(LOG_VariableAcquisitionWorker())
237 qCWarning(LOG_VariableAcquisitionWorker())
253 << tr("Impossible to retrieve AcquisitionRequest for the incoming data.");
238 << tr("Impossible to retrieve AcquisitionRequest for the incoming data.");
254 }
239 }
255 }
240 }
256
241
257 void VariableAcquisitionWorker::onExecuteRequest(QUuid acqIdentifier)
242 void VariableAcquisitionWorker::onExecuteRequest(QUuid acqIdentifier)
258 {
243 {
259 qCDebug(LOG_VariableAcquisitionWorker()) << tr("onExecuteRequest") << QThread::currentThread();
244 qCDebug(LOG_VariableAcquisitionWorker()) << tr("onExecuteRequest") << QThread::currentThread();
260 impl->lockRead();
245 impl->lockRead();
261 auto it = impl->m_AcqIdentifierToAcqRequestMap.find(acqIdentifier);
246 auto it = impl->m_AcqIdentifierToAcqRequestMap.find(acqIdentifier);
262 if (it != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
247 if (it != impl->m_AcqIdentifierToAcqRequestMap.cend()) {
263 auto request = it->second;
248 auto request = it->second;
264 impl->unlock();
249 impl->unlock();
265 emit variableRequestInProgress(request.m_vIdentifier, 0.1);
250 emit variableRequestInProgress(request.m_vIdentifier, 0.1);
266 qCDebug(LOG_VariableAcquisitionWorker()) << tr("Start request 10%") << acqIdentifier
251 qCDebug(LOG_VariableAcquisitionWorker()) << tr("Start request 10%") << acqIdentifier
267 << QThread::currentThread();
252 << QThread::currentThread();
268 request.m_Provider->requestDataLoading(acqIdentifier, request.m_DataProviderParameters);
253 request.m_Provider->requestDataLoading(acqIdentifier, request.m_DataProviderParameters);
269 }
254 }
270 else {
255 else {
271 impl->unlock();
256 impl->unlock();
272 // TODO log no acqIdentifier recognized
257 // TODO log no acqIdentifier recognized
273 }
258 }
274 }
259 }
275
260
276 void VariableAcquisitionWorker::initialize()
261 void VariableAcquisitionWorker::initialize()
277 {
262 {
278 qCDebug(LOG_VariableAcquisitionWorker()) << tr("VariableAcquisitionWorker init")
263 qCDebug(LOG_VariableAcquisitionWorker()) << tr("VariableAcquisitionWorker init")
279 << QThread::currentThread();
264 << QThread::currentThread();
280 impl->m_WorkingMutex.lock();
265 impl->m_WorkingMutex.lock();
281 qCDebug(LOG_VariableAcquisitionWorker()) << tr("VariableAcquisitionWorker init END");
266 qCDebug(LOG_VariableAcquisitionWorker()) << tr("VariableAcquisitionWorker init END");
282 }
267 }
283
268
284 void VariableAcquisitionWorker::finalize()
269 void VariableAcquisitionWorker::finalize()
285 {
270 {
286 impl->m_WorkingMutex.unlock();
271 impl->m_WorkingMutex.unlock();
287 }
272 }
288
273
289 void VariableAcquisitionWorker::waitForFinish()
274 void VariableAcquisitionWorker::waitForFinish()
290 {
275 {
291 QMutexLocker locker{&impl->m_WorkingMutex};
276 QMutexLocker locker{&impl->m_WorkingMutex};
292 }
277 }
293
278
294 void VariableAcquisitionWorker::VariableAcquisitionWorkerPrivate::removeVariableRequest(
279 void VariableAcquisitionWorker::VariableAcquisitionWorkerPrivate::removeVariableRequest(
295 QUuid vIdentifier)
280 QUuid vIdentifier)
296 {
281 {
297 lockWrite();
282 lockWrite();
298 auto it = m_VIdentifierToCurrrentAcqIdMap.find(vIdentifier);
283 auto it = m_VIdentifierToCurrrentAcqIdMap.find(vIdentifier);
299
284
300 if (it != m_VIdentifierToCurrrentAcqIdMap.cend()) {
285 if (it != m_VIdentifierToCurrrentAcqIdMap.cend()) {
301 // A current request already exists, we can replace the next one
286 // A current request already exists, we can replace the next one
302
287
303 qCDebug(LOG_VariableAcquisitionWorker())
288 qCDebug(LOG_VariableAcquisitionWorker())
304 << "VariableAcquisitionWorkerPrivate::removeVariableRequest "
289 << "VariableAcquisitionWorkerPrivate::removeVariableRequest "
305 << QThread::currentThread()->objectName() << it->second;
290 << QThread::currentThread()->objectName() << it->second;
306 m_AcqIdentifierToAcqRequestMap.erase(it->second);
291 m_AcqIdentifierToAcqRequestMap.erase(it->second);
307 m_AcqIdentifierToAcqDataPacketVectorMap.erase(it->second);
292 m_AcqIdentifierToAcqDataPacketVectorMap.erase(it->second);
308 }
293 }
309
294
310 // stop any progression
295 // stop any progression
311 emit q->variableRequestInProgress(vIdentifier, 0.0);
296 emit q->variableRequestInProgress(vIdentifier, 0.0);
312
297
313 m_VIdentifierToCurrrentAcqIdMap.erase(vIdentifier);
298 m_VIdentifierToCurrrentAcqIdMap.erase(vIdentifier);
314 unlock();
299 unlock();
315 }
300 }
316
301
317 void VariableAcquisitionWorker::VariableAcquisitionWorkerPrivate::cancelVarRequest(
302 void VariableAcquisitionWorker::VariableAcquisitionWorkerPrivate::cancelVarRequest(
318 QUuid varRequestId)
303 QUuid varRequestId)
319 {
304 {
320 qCDebug(LOG_VariableAcquisitionWorker())
305 qCDebug(LOG_VariableAcquisitionWorker())
321 << "VariableAcquisitionWorkerPrivate::cancelVarRequest 0";
306 << "VariableAcquisitionWorkerPrivate::cancelVarRequest start";
322 lockRead();
307 lockRead();
323 // get all AcqIdentifier in link with varRequestId
308 // get all AcqIdentifier in link with varRequestId
324 QVector<QUuid> acqIdsToRm;
309 QVector<QUuid> acqIdsToRm;
325 auto cend = m_AcqIdentifierToAcqRequestMap.cend();
310 auto cend = m_AcqIdentifierToAcqRequestMap.cend();
326 for (auto it = m_AcqIdentifierToAcqRequestMap.cbegin(); it != cend; ++it) {
311 for (auto it = m_AcqIdentifierToAcqRequestMap.cbegin(); it != cend; ++it) {
327 if (it->second.m_VarRequestId == varRequestId) {
312 if (it->second.m_VarRequestId == varRequestId) {
328 acqIdsToRm << it->first;
313 acqIdsToRm << it->first;
329 }
314 }
330 }
315 }
331 unlock();
316 unlock();
332 // run aborting or removing of acqIdsToRm
317 // run aborting or removing of acqIdsToRm
333
318
334 for (auto acqId : acqIdsToRm) {
319 for (auto acqId : acqIdsToRm) {
335 removeAcqRequest(acqId);
320 removeAcqRequest(acqId);
336 }
321 }
337 qCDebug(LOG_VariableAcquisitionWorker())
322 qCDebug(LOG_VariableAcquisitionWorker())
338 << "VariableAcquisitionWorkerPrivate::cancelVarRequest end";
323 << "VariableAcquisitionWorkerPrivate::cancelVarRequest end";
339 }
324 }
340
325
341 void VariableAcquisitionWorker::VariableAcquisitionWorkerPrivate::removeAcqRequest(
326 void VariableAcquisitionWorker::VariableAcquisitionWorkerPrivate::removeAcqRequest(
342 QUuid acqRequestId)
327 QUuid acqRequestId)
343 {
328 {
344 qCDebug(LOG_VariableAcquisitionWorker())
329 qCDebug(LOG_VariableAcquisitionWorker())
345 << "VariableAcquisitionWorkerPrivate::removeAcqRequest";
330 << "VariableAcquisitionWorkerPrivate::removeAcqRequest";
346 QUuid vIdentifier;
331 QUuid vIdentifier;
347 std::shared_ptr<IDataProvider> provider;
332 std::shared_ptr<IDataProvider> provider;
348 lockRead();
333 lockRead();
349 auto acqIt = m_AcqIdentifierToAcqRequestMap.find(acqRequestId);
334 auto acqIt = m_AcqIdentifierToAcqRequestMap.find(acqRequestId);
350 if (acqIt != m_AcqIdentifierToAcqRequestMap.cend()) {
335 if (acqIt != m_AcqIdentifierToAcqRequestMap.cend()) {
351 vIdentifier = acqIt->second.m_vIdentifier;
336 vIdentifier = acqIt->second.m_vIdentifier;
352 provider = acqIt->second.m_Provider;
337 provider = acqIt->second.m_Provider;
353
338
354 auto it = m_VIdentifierToCurrrentAcqIdMap.find(vIdentifier);
339 auto it = m_VIdentifierToCurrrentAcqIdMap.find(vIdentifier);
355 if (it != m_VIdentifierToCurrrentAcqIdMap.cend()) {
340 if (it != m_VIdentifierToCurrrentAcqIdMap.cend()) {
356 if (it->second == acqRequestId) {
341 if (it->second == acqRequestId) {
357 // acqRequest is currently running -> let's aborting it
342 // acqRequest is currently running -> let's aborting it
358 unlock();
343 unlock();
359
344
360 // notify the request aborting to the provider
345 // notify the request aborting to the provider
361 provider->requestDataAborting(acqRequestId);
346 provider->requestDataAborting(acqRequestId);
362 }
347 }
363 else {
348 else {
364 unlock();
349 unlock();
365 }
350 }
366 }
351 }
367 else {
352 else {
368 unlock();
353 unlock();
369 }
354 }
370 }
355 }
371 else {
356 else {
372 unlock();
357 unlock();
373 }
358 }
374
359
375 lockWrite();
360 lockWrite();
376
361
377 qCDebug(LOG_VariableAcquisitionWorker())
378 << "VariableAcquisitionWorkerPrivate::updateToNextRequest removeAcqRequest: "
379 << acqRequestId;
380 m_AcqIdentifierToAcqDataPacketVectorMap.erase(acqRequestId);
362 m_AcqIdentifierToAcqDataPacketVectorMap.erase(acqRequestId);
381 m_AcqIdentifierToAcqRequestMap.erase(acqRequestId);
363 m_AcqIdentifierToAcqRequestMap.erase(acqRequestId);
382
364
383 unlock();
365 unlock();
384 qCDebug(LOG_VariableAcquisitionWorker())
366 qCDebug(LOG_VariableAcquisitionWorker())
385 << "VariableAcquisitionWorkerPrivate::removeAcqRequest END";
367 << "VariableAcquisitionWorkerPrivate::removeAcqRequest END";
386 }
368 }
@@ -1,1085 +1,1092
1 #include <Variable/Variable.h>
1 #include <Variable/Variable.h>
2 #include <Variable/VariableAcquisitionWorker.h>
2 #include <Variable/VariableAcquisitionWorker.h>
3 #include <Variable/VariableCacheStrategy.h>
3 #include <Variable/VariableCacheStrategy.h>
4 #include <Variable/VariableCacheStrategyFactory.h>
4 #include <Variable/VariableCacheStrategyFactory.h>
5 #include <Variable/VariableController.h>
5 #include <Variable/VariableController.h>
6 #include <Variable/VariableModel.h>
6 #include <Variable/VariableModel.h>
7 #include <Variable/VariableSynchronizationGroup.h>
7 #include <Variable/VariableSynchronizationGroup.h>
8
8
9 #include <Data/DataProviderParameters.h>
9 #include <Data/DataProviderParameters.h>
10 #include <Data/IDataProvider.h>
10 #include <Data/IDataProvider.h>
11 #include <Data/IDataSeries.h>
11 #include <Data/IDataSeries.h>
12 #include <Data/VariableRequest.h>
12 #include <Data/VariableRequest.h>
13 #include <Time/TimeController.h>
13 #include <Time/TimeController.h>
14
14
15 #include <QDataStream>
15 #include <QDataStream>
16 #include <QMutex>
16 #include <QMutex>
17 #include <QThread>
17 #include <QThread>
18 #include <QUuid>
18 #include <QUuid>
19 #include <QtCore/QItemSelectionModel>
19 #include <QtCore/QItemSelectionModel>
20
20
21 #include <deque>
21 #include <deque>
22 #include <set>
22 #include <set>
23 #include <unordered_map>
23 #include <unordered_map>
24
24
25 Q_LOGGING_CATEGORY(LOG_VariableController, "VariableController")
25 Q_LOGGING_CATEGORY(LOG_VariableController, "VariableController")
26
26
27 namespace {
27 namespace {
28
28
29 SqpRange computeSynchroRangeRequested(const SqpRange &varRange, const SqpRange &graphRange,
29 SqpRange computeSynchroRangeRequested(const SqpRange &varRange, const SqpRange &graphRange,
30 const SqpRange &oldGraphRange)
30 const SqpRange &oldGraphRange)
31 {
31 {
32 auto zoomType = VariableController::getZoomType(graphRange, oldGraphRange);
32 auto zoomType = VariableController::getZoomType(graphRange, oldGraphRange);
33
33
34 auto varRangeRequested = varRange;
34 auto varRangeRequested = varRange;
35 switch (zoomType) {
35 switch (zoomType) {
36 case AcquisitionZoomType::ZoomIn: {
36 case AcquisitionZoomType::ZoomIn: {
37 auto deltaLeft = graphRange.m_TStart - oldGraphRange.m_TStart;
37 auto deltaLeft = graphRange.m_TStart - oldGraphRange.m_TStart;
38 auto deltaRight = oldGraphRange.m_TEnd - graphRange.m_TEnd;
38 auto deltaRight = oldGraphRange.m_TEnd - graphRange.m_TEnd;
39 varRangeRequested.m_TStart += deltaLeft;
39 varRangeRequested.m_TStart += deltaLeft;
40 varRangeRequested.m_TEnd -= deltaRight;
40 varRangeRequested.m_TEnd -= deltaRight;
41 break;
41 break;
42 }
42 }
43
43
44 case AcquisitionZoomType::ZoomOut: {
44 case AcquisitionZoomType::ZoomOut: {
45 auto deltaLeft = oldGraphRange.m_TStart - graphRange.m_TStart;
45 auto deltaLeft = oldGraphRange.m_TStart - graphRange.m_TStart;
46 auto deltaRight = graphRange.m_TEnd - oldGraphRange.m_TEnd;
46 auto deltaRight = graphRange.m_TEnd - oldGraphRange.m_TEnd;
47 varRangeRequested.m_TStart -= deltaLeft;
47 varRangeRequested.m_TStart -= deltaLeft;
48 varRangeRequested.m_TEnd += deltaRight;
48 varRangeRequested.m_TEnd += deltaRight;
49 break;
49 break;
50 }
50 }
51 case AcquisitionZoomType::PanRight: {
51 case AcquisitionZoomType::PanRight: {
52 auto deltaLeft = graphRange.m_TStart - oldGraphRange.m_TStart;
52 auto deltaLeft = graphRange.m_TStart - oldGraphRange.m_TStart;
53 auto deltaRight = graphRange.m_TEnd - oldGraphRange.m_TEnd;
53 auto deltaRight = graphRange.m_TEnd - oldGraphRange.m_TEnd;
54 varRangeRequested.m_TStart += deltaLeft;
54 varRangeRequested.m_TStart += deltaLeft;
55 varRangeRequested.m_TEnd += deltaRight;
55 varRangeRequested.m_TEnd += deltaRight;
56 break;
56 break;
57 }
57 }
58 case AcquisitionZoomType::PanLeft: {
58 case AcquisitionZoomType::PanLeft: {
59 auto deltaLeft = oldGraphRange.m_TStart - graphRange.m_TStart;
59 auto deltaLeft = oldGraphRange.m_TStart - graphRange.m_TStart;
60 auto deltaRight = oldGraphRange.m_TEnd - graphRange.m_TEnd;
60 auto deltaRight = oldGraphRange.m_TEnd - graphRange.m_TEnd;
61 varRangeRequested.m_TStart -= deltaLeft;
61 varRangeRequested.m_TStart -= deltaLeft;
62 varRangeRequested.m_TEnd -= deltaRight;
62 varRangeRequested.m_TEnd -= deltaRight;
63 break;
63 break;
64 }
64 }
65 case AcquisitionZoomType::Unknown: {
65 case AcquisitionZoomType::Unknown: {
66 qCCritical(LOG_VariableController())
66 qCCritical(LOG_VariableController())
67 << VariableController::tr("Impossible to synchronize: zoom type unknown");
67 << VariableController::tr("Impossible to synchronize: zoom type unknown");
68 break;
68 break;
69 }
69 }
70 default:
70 default:
71 qCCritical(LOG_VariableController()) << VariableController::tr(
71 qCCritical(LOG_VariableController()) << VariableController::tr(
72 "Impossible to synchronize: zoom type not take into account");
72 "Impossible to synchronize: zoom type not take into account");
73 // No action
73 // No action
74 break;
74 break;
75 }
75 }
76
76
77 return varRangeRequested;
77 return varRangeRequested;
78 }
78 }
79 }
79 }
80
80
81 enum class VariableRequestHandlerState { OFF, RUNNING, PENDING };
81 enum class VariableRequestHandlerState { OFF, RUNNING, PENDING };
82
82
83 struct VariableRequestHandler {
83 struct VariableRequestHandler {
84
84
85 VariableRequestHandler()
85 VariableRequestHandler()
86 {
86 {
87 m_CanUpdate = false;
87 m_CanUpdate = false;
88 m_State = VariableRequestHandlerState::OFF;
88 m_State = VariableRequestHandlerState::OFF;
89 }
89 }
90
90
91 QUuid m_VarId;
91 QUuid m_VarId;
92 VariableRequest m_RunningVarRequest;
92 VariableRequest m_RunningVarRequest;
93 VariableRequest m_PendingVarRequest;
93 VariableRequest m_PendingVarRequest;
94 VariableRequestHandlerState m_State;
94 VariableRequestHandlerState m_State;
95 bool m_CanUpdate;
95 bool m_CanUpdate;
96 };
96 };
97
97
98 struct VariableController::VariableControllerPrivate {
98 struct VariableController::VariableControllerPrivate {
99 explicit VariableControllerPrivate(VariableController *parent)
99 explicit VariableControllerPrivate(VariableController *parent)
100 : m_WorkingMutex{},
100 : m_WorkingMutex{},
101 m_VariableModel{new VariableModel{parent}},
101 m_VariableModel{new VariableModel{parent}},
102 m_VariableSelectionModel{new QItemSelectionModel{m_VariableModel, parent}},
102 m_VariableSelectionModel{new QItemSelectionModel{m_VariableModel, parent}},
103 // m_VariableCacheStrategy{std::make_unique<VariableCacheStrategy>()},
103 // m_VariableCacheStrategy{std::make_unique<VariableCacheStrategy>()},
104 m_VariableCacheStrategy{VariableCacheStrategyFactory::createCacheStrategy(
104 m_VariableCacheStrategy{VariableCacheStrategyFactory::createCacheStrategy(
105 CacheStrategy::SingleThreshold)},
105 CacheStrategy::SingleThreshold)},
106 m_VariableAcquisitionWorker{std::make_unique<VariableAcquisitionWorker>()},
106 m_VariableAcquisitionWorker{std::make_unique<VariableAcquisitionWorker>()},
107 q{parent}
107 q{parent}
108 {
108 {
109
109
110 m_VariableAcquisitionWorker->moveToThread(&m_VariableAcquisitionWorkerThread);
110 m_VariableAcquisitionWorker->moveToThread(&m_VariableAcquisitionWorkerThread);
111 m_VariableAcquisitionWorkerThread.setObjectName("VariableAcquisitionWorkerThread");
111 m_VariableAcquisitionWorkerThread.setObjectName("VariableAcquisitionWorkerThread");
112 }
112 }
113
113
114
114
115 virtual ~VariableControllerPrivate()
115 virtual ~VariableControllerPrivate()
116 {
116 {
117 qCDebug(LOG_VariableController()) << tr("VariableControllerPrivate destruction");
117 qCDebug(LOG_VariableController()) << tr("VariableControllerPrivate destruction");
118 m_VariableAcquisitionWorkerThread.quit();
118 m_VariableAcquisitionWorkerThread.quit();
119 m_VariableAcquisitionWorkerThread.wait();
119 m_VariableAcquisitionWorkerThread.wait();
120 }
120 }
121
121
122
122
123 void processRequest(std::shared_ptr<Variable> var, const SqpRange &rangeRequested,
123 void processRequest(std::shared_ptr<Variable> var, const SqpRange &rangeRequested,
124 QUuid varRequestId);
124 QUuid varRequestId);
125
125
126 std::shared_ptr<Variable> findVariable(QUuid vIdentifier);
126 std::shared_ptr<Variable> findVariable(QUuid vIdentifier);
127 std::shared_ptr<IDataSeries>
127 std::shared_ptr<IDataSeries>
128 retrieveDataSeries(const QVector<AcquisitionDataPacket> acqDataPacketVector);
128 retrieveDataSeries(const QVector<AcquisitionDataPacket> acqDataPacketVector);
129
129
130 void registerProvider(std::shared_ptr<IDataProvider> provider);
130 void registerProvider(std::shared_ptr<IDataProvider> provider);
131
131
132 void storeVariableRequest(QUuid varId, QUuid varRequestId, const VariableRequest &varRequest);
132 void storeVariableRequest(QUuid varId, QUuid varRequestId, const VariableRequest &varRequest);
133 QUuid acceptVariableRequest(QUuid varId, std::shared_ptr<IDataSeries> dataSeries);
133 QUuid acceptVariableRequest(QUuid varId, std::shared_ptr<IDataSeries> dataSeries);
134 void updateVariables(QUuid varRequestId);
134 void updateVariables(QUuid varRequestId);
135 void updateVariableRequest(QUuid varRequestId);
135 void updateVariableRequest(QUuid varRequestId);
136 void cancelVariableRequest(QUuid varRequestId);
136 void cancelVariableRequest(QUuid varRequestId);
137 void executeVarRequest(std::shared_ptr<Variable> var, VariableRequest &varRequest);
137 void executeVarRequest(std::shared_ptr<Variable> var, VariableRequest &varRequest);
138
138
139 template <typename VariableIterator>
139 template <typename VariableIterator>
140 void desynchronize(VariableIterator variableIt, const QUuid &syncGroupId);
140 void desynchronize(VariableIterator variableIt, const QUuid &syncGroupId);
141
141
142 QMutex m_WorkingMutex;
142 QMutex m_WorkingMutex;
143 /// Variable model. The VariableController has the ownership
143 /// Variable model. The VariableController has the ownership
144 VariableModel *m_VariableModel;
144 VariableModel *m_VariableModel;
145 QItemSelectionModel *m_VariableSelectionModel;
145 QItemSelectionModel *m_VariableSelectionModel;
146
146
147
147
148 TimeController *m_TimeController{nullptr};
148 TimeController *m_TimeController{nullptr};
149 std::unique_ptr<VariableCacheStrategy> m_VariableCacheStrategy;
149 std::unique_ptr<VariableCacheStrategy> m_VariableCacheStrategy;
150 std::unique_ptr<VariableAcquisitionWorker> m_VariableAcquisitionWorker;
150 std::unique_ptr<VariableAcquisitionWorker> m_VariableAcquisitionWorker;
151 QThread m_VariableAcquisitionWorkerThread;
151 QThread m_VariableAcquisitionWorkerThread;
152
152
153 std::unordered_map<std::shared_ptr<Variable>, std::shared_ptr<IDataProvider> >
153 std::unordered_map<std::shared_ptr<Variable>, std::shared_ptr<IDataProvider> >
154 m_VariableToProviderMap;
154 m_VariableToProviderMap;
155 std::unordered_map<std::shared_ptr<Variable>, QUuid> m_VariableToIdentifierMap;
155 std::unordered_map<std::shared_ptr<Variable>, QUuid> m_VariableToIdentifierMap;
156 std::map<QUuid, std::shared_ptr<VariableSynchronizationGroup> >
156 std::map<QUuid, std::shared_ptr<VariableSynchronizationGroup> >
157 m_GroupIdToVariableSynchronizationGroupMap;
157 m_GroupIdToVariableSynchronizationGroupMap;
158 std::map<QUuid, QUuid> m_VariableIdGroupIdMap;
158 std::map<QUuid, QUuid> m_VariableIdGroupIdMap;
159 std::set<std::shared_ptr<IDataProvider> > m_ProviderSet;
159 std::set<std::shared_ptr<IDataProvider> > m_ProviderSet;
160
160
161 std::map<QUuid, std::list<QUuid> > m_VarGroupIdToVarIds;
161 std::map<QUuid, std::list<QUuid> > m_VarGroupIdToVarIds;
162 std::map<QUuid, std::unique_ptr<VariableRequestHandler> > m_VarIdToVarRequestHandler;
162 std::map<QUuid, std::unique_ptr<VariableRequestHandler> > m_VarIdToVarRequestHandler;
163
163
164 VariableController *q;
164 VariableController *q;
165 };
165 };
166
166
167
167
168 VariableController::VariableController(QObject *parent)
168 VariableController::VariableController(QObject *parent)
169 : QObject{parent}, impl{spimpl::make_unique_impl<VariableControllerPrivate>(this)}
169 : QObject{parent}, impl{spimpl::make_unique_impl<VariableControllerPrivate>(this)}
170 {
170 {
171 qCDebug(LOG_VariableController()) << tr("VariableController construction")
171 qCDebug(LOG_VariableController()) << tr("VariableController construction")
172 << QThread::currentThread();
172 << QThread::currentThread();
173
173
174 connect(impl->m_VariableModel, &VariableModel::abortProgessRequested, this,
174 connect(impl->m_VariableModel, &VariableModel::abortProgessRequested, this,
175 &VariableController::onAbortProgressRequested);
175 &VariableController::onAbortProgressRequested);
176
176
177 connect(impl->m_VariableAcquisitionWorker.get(),
177 connect(impl->m_VariableAcquisitionWorker.get(),
178 &VariableAcquisitionWorker::variableCanceledRequested, this,
178 &VariableAcquisitionWorker::variableCanceledRequested, this,
179 &VariableController::onAbortAcquisitionRequested);
179 &VariableController::onAbortAcquisitionRequested);
180
180
181 connect(impl->m_VariableAcquisitionWorker.get(), &VariableAcquisitionWorker::dataProvided, this,
181 connect(impl->m_VariableAcquisitionWorker.get(), &VariableAcquisitionWorker::dataProvided, this,
182 &VariableController::onDataProvided);
182 &VariableController::onDataProvided);
183 connect(impl->m_VariableAcquisitionWorker.get(),
183 connect(impl->m_VariableAcquisitionWorker.get(),
184 &VariableAcquisitionWorker::variableRequestInProgress, this,
184 &VariableAcquisitionWorker::variableRequestInProgress, this,
185 &VariableController::onVariableRetrieveDataInProgress);
185 &VariableController::onVariableRetrieveDataInProgress);
186
186
187
187
188 connect(&impl->m_VariableAcquisitionWorkerThread, &QThread::started,
188 connect(&impl->m_VariableAcquisitionWorkerThread, &QThread::started,
189 impl->m_VariableAcquisitionWorker.get(), &VariableAcquisitionWorker::initialize);
189 impl->m_VariableAcquisitionWorker.get(), &VariableAcquisitionWorker::initialize);
190 connect(&impl->m_VariableAcquisitionWorkerThread, &QThread::finished,
190 connect(&impl->m_VariableAcquisitionWorkerThread, &QThread::finished,
191 impl->m_VariableAcquisitionWorker.get(), &VariableAcquisitionWorker::finalize);
191 impl->m_VariableAcquisitionWorker.get(), &VariableAcquisitionWorker::finalize);
192
192
193 connect(impl->m_VariableModel, &VariableModel::requestVariableRangeUpdate, this,
193 connect(impl->m_VariableModel, &VariableModel::requestVariableRangeUpdate, this,
194 &VariableController::onUpdateDateTime);
194 &VariableController::onUpdateDateTime);
195
195
196 impl->m_VariableAcquisitionWorkerThread.start();
196 impl->m_VariableAcquisitionWorkerThread.start();
197 }
197 }
198
198
199 VariableController::~VariableController()
199 VariableController::~VariableController()
200 {
200 {
201 qCDebug(LOG_VariableController()) << tr("VariableController destruction")
201 qCDebug(LOG_VariableController()) << tr("VariableController destruction")
202 << QThread::currentThread();
202 << QThread::currentThread();
203 this->waitForFinish();
203 this->waitForFinish();
204 }
204 }
205
205
206 VariableModel *VariableController::variableModel() noexcept
206 VariableModel *VariableController::variableModel() noexcept
207 {
207 {
208 return impl->m_VariableModel;
208 return impl->m_VariableModel;
209 }
209 }
210
210
211 QItemSelectionModel *VariableController::variableSelectionModel() noexcept
211 QItemSelectionModel *VariableController::variableSelectionModel() noexcept
212 {
212 {
213 return impl->m_VariableSelectionModel;
213 return impl->m_VariableSelectionModel;
214 }
214 }
215
215
216 void VariableController::setTimeController(TimeController *timeController) noexcept
216 void VariableController::setTimeController(TimeController *timeController) noexcept
217 {
217 {
218 impl->m_TimeController = timeController;
218 impl->m_TimeController = timeController;
219 }
219 }
220
220
221 std::shared_ptr<Variable>
221 std::shared_ptr<Variable>
222 VariableController::cloneVariable(std::shared_ptr<Variable> variable) noexcept
222 VariableController::cloneVariable(std::shared_ptr<Variable> variable) noexcept
223 {
223 {
224 if (impl->m_VariableModel->containsVariable(variable)) {
224 if (impl->m_VariableModel->containsVariable(variable)) {
225 // Clones variable
225 // Clones variable
226 auto duplicate = variable->clone();
226 auto duplicate = variable->clone();
227
227
228 // Adds clone to model
228 // Adds clone to model
229 impl->m_VariableModel->addVariable(duplicate);
229 impl->m_VariableModel->addVariable(duplicate);
230
230
231 // Generates clone identifier
231 // Generates clone identifier
232 impl->m_VariableToIdentifierMap[duplicate] = QUuid::createUuid();
232 impl->m_VariableToIdentifierMap[duplicate] = QUuid::createUuid();
233
233
234 // Registers provider
234 // Registers provider
235 auto variableProvider = impl->m_VariableToProviderMap.at(variable);
235 auto variableProvider = impl->m_VariableToProviderMap.at(variable);
236 auto duplicateProvider = variableProvider != nullptr ? variableProvider->clone() : nullptr;
236 auto duplicateProvider = variableProvider != nullptr ? variableProvider->clone() : nullptr;
237
237
238 impl->m_VariableToProviderMap[duplicate] = duplicateProvider;
238 impl->m_VariableToProviderMap[duplicate] = duplicateProvider;
239 if (duplicateProvider) {
239 if (duplicateProvider) {
240 impl->registerProvider(duplicateProvider);
240 impl->registerProvider(duplicateProvider);
241 }
241 }
242
242
243 return duplicate;
243 return duplicate;
244 }
244 }
245 else {
245 else {
246 qCCritical(LOG_VariableController())
246 qCCritical(LOG_VariableController())
247 << tr("Can't create duplicate of variable %1: variable not registered in the model")
247 << tr("Can't create duplicate of variable %1: variable not registered in the model")
248 .arg(variable->name());
248 .arg(variable->name());
249 return nullptr;
249 return nullptr;
250 }
250 }
251 }
251 }
252
252
253 void VariableController::deleteVariable(std::shared_ptr<Variable> variable) noexcept
253 void VariableController::deleteVariable(std::shared_ptr<Variable> variable) noexcept
254 {
254 {
255 if (!variable) {
255 if (!variable) {
256 qCCritical(LOG_VariableController()) << "Can't delete variable: variable is null";
256 qCCritical(LOG_VariableController()) << "Can't delete variable: variable is null";
257 return;
257 return;
258 }
258 }
259
259
260 // Spreads in SciQlop that the variable will be deleted, so that potential receivers can
260 // Spreads in SciQlop that the variable will be deleted, so that potential receivers can
261 // make some treatments before the deletion
261 // make some treatments before the deletion
262 emit variableAboutToBeDeleted(variable);
262 emit variableAboutToBeDeleted(variable);
263
263
264 auto variableIt = impl->m_VariableToIdentifierMap.find(variable);
264 auto variableIt = impl->m_VariableToIdentifierMap.find(variable);
265 Q_ASSERT(variableIt != impl->m_VariableToIdentifierMap.cend());
265 Q_ASSERT(variableIt != impl->m_VariableToIdentifierMap.cend());
266
266
267 auto variableId = variableIt->second;
267 auto variableId = variableIt->second;
268
268
269 // Removes variable's handler
269 // Removes variable's handler
270 impl->m_VarIdToVarRequestHandler.erase(variableId);
270 impl->m_VarIdToVarRequestHandler.erase(variableId);
271
271
272 // Desynchronizes variable (if the variable is in a sync group)
272 // Desynchronizes variable (if the variable is in a sync group)
273 auto syncGroupIt = impl->m_VariableIdGroupIdMap.find(variableId);
273 auto syncGroupIt = impl->m_VariableIdGroupIdMap.find(variableId);
274 if (syncGroupIt != impl->m_VariableIdGroupIdMap.cend()) {
274 if (syncGroupIt != impl->m_VariableIdGroupIdMap.cend()) {
275 impl->desynchronize(variableIt, syncGroupIt->second);
275 impl->desynchronize(variableIt, syncGroupIt->second);
276 }
276 }
277
277
278 // Deletes identifier
278 // Deletes identifier
279 impl->m_VariableToIdentifierMap.erase(variableIt);
279 impl->m_VariableToIdentifierMap.erase(variableIt);
280
280
281 // Deletes provider
281 // Deletes provider
282 auto nbProvidersDeleted = impl->m_VariableToProviderMap.erase(variable);
282 auto nbProvidersDeleted = impl->m_VariableToProviderMap.erase(variable);
283 qCDebug(LOG_VariableController())
283 qCDebug(LOG_VariableController())
284 << tr("Number of providers deleted for variable %1: %2")
284 << tr("Number of providers deleted for variable %1: %2")
285 .arg(variable->name(), QString::number(nbProvidersDeleted));
285 .arg(variable->name(), QString::number(nbProvidersDeleted));
286
286
287
287
288 // Deletes from model
288 // Deletes from model
289 impl->m_VariableModel->deleteVariable(variable);
289 impl->m_VariableModel->deleteVariable(variable);
290 }
290 }
291
291
292 void VariableController::deleteVariables(
292 void VariableController::deleteVariables(
293 const QVector<std::shared_ptr<Variable> > &variables) noexcept
293 const QVector<std::shared_ptr<Variable> > &variables) noexcept
294 {
294 {
295 for (auto variable : qAsConst(variables)) {
295 for (auto variable : qAsConst(variables)) {
296 deleteVariable(variable);
296 deleteVariable(variable);
297 }
297 }
298 }
298 }
299
299
300 QByteArray
300 QByteArray
301 VariableController::mimeDataForVariables(const QList<std::shared_ptr<Variable> > &variables) const
301 VariableController::mimeDataForVariables(const QList<std::shared_ptr<Variable> > &variables) const
302 {
302 {
303 auto encodedData = QByteArray{};
303 auto encodedData = QByteArray{};
304
304
305 QVariantList ids;
305 QVariantList ids;
306 for (auto &var : variables) {
306 for (auto &var : variables) {
307 auto itVar = impl->m_VariableToIdentifierMap.find(var);
307 auto itVar = impl->m_VariableToIdentifierMap.find(var);
308 if (itVar == impl->m_VariableToIdentifierMap.cend()) {
308 if (itVar == impl->m_VariableToIdentifierMap.cend()) {
309 qCCritical(LOG_VariableController())
309 qCCritical(LOG_VariableController())
310 << tr("Impossible to find the data for an unknown variable.");
310 << tr("Impossible to find the data for an unknown variable.");
311 }
311 }
312
312
313 ids << itVar->second.toByteArray();
313 ids << itVar->second.toByteArray();
314 }
314 }
315
315
316 QDataStream stream{&encodedData, QIODevice::WriteOnly};
316 QDataStream stream{&encodedData, QIODevice::WriteOnly};
317 stream << ids;
317 stream << ids;
318
318
319 return encodedData;
319 return encodedData;
320 }
320 }
321
321
322 QList<std::shared_ptr<Variable> >
322 QList<std::shared_ptr<Variable> >
323 VariableController::variablesForMimeData(const QByteArray &mimeData) const
323 VariableController::variablesForMimeData(const QByteArray &mimeData) const
324 {
324 {
325 auto variables = QList<std::shared_ptr<Variable> >{};
325 auto variables = QList<std::shared_ptr<Variable> >{};
326 QDataStream stream{mimeData};
326 QDataStream stream{mimeData};
327
327
328 QVariantList ids;
328 QVariantList ids;
329 stream >> ids;
329 stream >> ids;
330
330
331 for (auto id : ids) {
331 for (auto id : ids) {
332 auto uuid = QUuid{id.toByteArray()};
332 auto uuid = QUuid{id.toByteArray()};
333 auto var = impl->findVariable(uuid);
333 auto var = impl->findVariable(uuid);
334 variables << var;
334 variables << var;
335 }
335 }
336
336
337 return variables;
337 return variables;
338 }
338 }
339
339
340 std::shared_ptr<Variable>
340 std::shared_ptr<Variable>
341 VariableController::createVariable(const QString &name, const QVariantHash &metadata,
341 VariableController::createVariable(const QString &name, const QVariantHash &metadata,
342 std::shared_ptr<IDataProvider> provider) noexcept
342 std::shared_ptr<IDataProvider> provider) noexcept
343 {
343 {
344 if (!impl->m_TimeController) {
344 if (!impl->m_TimeController) {
345 qCCritical(LOG_VariableController())
345 qCCritical(LOG_VariableController())
346 << tr("Impossible to create variable: The time controller is null");
346 << tr("Impossible to create variable: The time controller is null");
347 return nullptr;
347 return nullptr;
348 }
348 }
349
349
350 auto range = impl->m_TimeController->dateTime();
350 auto range = impl->m_TimeController->dateTime();
351
351
352 if (auto newVariable = impl->m_VariableModel->createVariable(name, metadata)) {
352 if (auto newVariable = impl->m_VariableModel->createVariable(name, metadata)) {
353 auto varId = QUuid::createUuid();
353 auto varId = QUuid::createUuid();
354
354
355 // Create the handler
355 // Create the handler
356 auto varRequestHandler = std::make_unique<VariableRequestHandler>();
356 auto varRequestHandler = std::make_unique<VariableRequestHandler>();
357 varRequestHandler->m_VarId = varId;
357 varRequestHandler->m_VarId = varId;
358
358
359 impl->m_VarIdToVarRequestHandler.insert(
359 impl->m_VarIdToVarRequestHandler.insert(
360 std::make_pair(varId, std::move(varRequestHandler)));
360 std::make_pair(varId, std::move(varRequestHandler)));
361
361
362 // store the provider
362 // store the provider
363 impl->registerProvider(provider);
363 impl->registerProvider(provider);
364
364
365 // Associate the provider
365 // Associate the provider
366 impl->m_VariableToProviderMap[newVariable] = provider;
366 impl->m_VariableToProviderMap[newVariable] = provider;
367 impl->m_VariableToIdentifierMap[newVariable] = varId;
367 impl->m_VariableToIdentifierMap[newVariable] = varId;
368
368
369 this->onRequestDataLoading(QVector<std::shared_ptr<Variable> >{newVariable}, range, false);
369 this->onRequestDataLoading(QVector<std::shared_ptr<Variable> >{newVariable}, range, false);
370
370
371 emit variableAdded(newVariable);
371 emit variableAdded(newVariable);
372
372
373 return newVariable;
373 return newVariable;
374 }
374 }
375
375
376 qCCritical(LOG_VariableController()) << tr("Impossible to create variable");
376 qCCritical(LOG_VariableController()) << tr("Impossible to create variable");
377 return nullptr;
377 return nullptr;
378 }
378 }
379
379
380 void VariableController::onDateTimeOnSelection(const SqpRange &dateTime)
380 void VariableController::onDateTimeOnSelection(const SqpRange &dateTime)
381 {
381 {
382 // NOTE: Even if acquisition request is aborting, the graphe range will be changed
382 // NOTE: Even if acquisition request is aborting, the graphe range will be changed
383 qCDebug(LOG_VariableController()) << "VariableController::onDateTimeOnSelection"
383 qCDebug(LOG_VariableController()) << "VariableController::onDateTimeOnSelection"
384 << QThread::currentThread()->objectName();
384 << QThread::currentThread()->objectName();
385 auto selectedRows = impl->m_VariableSelectionModel->selectedRows();
385 auto selectedRows = impl->m_VariableSelectionModel->selectedRows();
386
386
387 // NOTE we only permit the time modification for one variable
387 // NOTE we only permit the time modification for one variable
388 if (selectedRows.size() == 1) {
388 if (selectedRows.size() == 1) {
389
389
390 if (auto selectedVariable
390 if (auto selectedVariable
391 = impl->m_VariableModel->variable(qAsConst(selectedRows).first().row())) {
391 = impl->m_VariableModel->variable(qAsConst(selectedRows).first().row())) {
392
392
393 onUpdateDateTime(selectedVariable, dateTime);
393 onUpdateDateTime(selectedVariable, dateTime);
394 }
394 }
395 }
395 }
396 else if (selectedRows.size() > 1) {
396 else if (selectedRows.size() > 1) {
397 qCCritical(LOG_VariableController())
397 qCCritical(LOG_VariableController())
398 << tr("Impossible to set time for more than 1 variable in the same time");
398 << tr("Impossible to set time for more than 1 variable in the same time");
399 }
399 }
400 else {
400 else {
401 qCWarning(LOG_VariableController())
401 qCWarning(LOG_VariableController())
402 << tr("There is no variable selected to set the time one");
402 << tr("There is no variable selected to set the time one");
403 }
403 }
404 }
404 }
405
405
406 void VariableController::onUpdateDateTime(std::shared_ptr<Variable> variable,
406 void VariableController::onUpdateDateTime(std::shared_ptr<Variable> variable,
407 const SqpRange &dateTime)
407 const SqpRange &dateTime)
408 {
408 {
409 auto itVar = impl->m_VariableToIdentifierMap.find(variable);
409 auto itVar = impl->m_VariableToIdentifierMap.find(variable);
410 if (itVar == impl->m_VariableToIdentifierMap.cend()) {
410 if (itVar == impl->m_VariableToIdentifierMap.cend()) {
411 qCCritical(LOG_VariableController())
411 qCCritical(LOG_VariableController())
412 << tr("Impossible to onDateTimeOnSelection request for unknown variable");
412 << tr("Impossible to onDateTimeOnSelection request for unknown variable");
413 return;
413 return;
414 }
414 }
415
415
416 // notify that rescale operation has to be done
416 // notify that rescale operation has to be done
417 emit rangeChanged(variable, dateTime);
417 emit rangeChanged(variable, dateTime);
418
418
419 auto synchro
419 auto synchro
420 = impl->m_VariableIdGroupIdMap.find(itVar->second) != impl->m_VariableIdGroupIdMap.cend();
420 = impl->m_VariableIdGroupIdMap.find(itVar->second) != impl->m_VariableIdGroupIdMap.cend();
421
421
422 this->onRequestDataLoading(QVector<std::shared_ptr<Variable> >{variable}, dateTime, synchro);
422 this->onRequestDataLoading(QVector<std::shared_ptr<Variable> >{variable}, dateTime, synchro);
423 }
423 }
424
424
425 void VariableController::onDataProvided(QUuid vIdentifier,
425 void VariableController::onDataProvided(QUuid vIdentifier,
426 QVector<AcquisitionDataPacket> dataAcquired)
426 QVector<AcquisitionDataPacket> dataAcquired)
427 {
427 {
428 qCDebug(LOG_VariableController()) << tr("onDataProvided") << QThread::currentThread();
428 qCDebug(LOG_VariableController()) << tr("onDataProvided") << QThread::currentThread();
429 auto retrievedDataSeries = impl->retrieveDataSeries(dataAcquired);
429 auto retrievedDataSeries = impl->retrieveDataSeries(dataAcquired);
430 auto varRequestId = impl->acceptVariableRequest(vIdentifier, retrievedDataSeries);
430 auto varRequestId = impl->acceptVariableRequest(vIdentifier, retrievedDataSeries);
431 if (!varRequestId.isNull()) {
431 if (!varRequestId.isNull()) {
432 impl->updateVariables(varRequestId);
432 impl->updateVariables(varRequestId);
433 }
433 }
434 }
434 }
435
435
436 void VariableController::onVariableRetrieveDataInProgress(QUuid identifier, double progress)
436 void VariableController::onVariableRetrieveDataInProgress(QUuid identifier, double progress)
437 {
437 {
438 qCDebug(LOG_VariableController())
438 qCDebug(LOG_VariableController())
439 << "TORM: variableController::onVariableRetrieveDataInProgress"
439 << "TORM: variableController::onVariableRetrieveDataInProgress"
440 << QThread::currentThread()->objectName() << progress;
440 << QThread::currentThread()->objectName() << progress;
441 if (auto var = impl->findVariable(identifier)) {
441 if (auto var = impl->findVariable(identifier)) {
442 qCDebug(LOG_VariableController())
442 qCDebug(LOG_VariableController())
443 << "TORM: variableController::onVariableRetrieveDataInProgress FOUND";
443 << "TORM: variableController::onVariableRetrieveDataInProgress FOUND";
444 impl->m_VariableModel->setDataProgress(var, progress);
444 impl->m_VariableModel->setDataProgress(var, progress);
445 }
445 }
446 else {
446 else {
447 qCCritical(LOG_VariableController())
447 qCCritical(LOG_VariableController())
448 << tr("Impossible to notify progression of a null variable");
448 << tr("Impossible to notify progression of a null variable");
449 }
449 }
450 }
450 }
451
451
452 void VariableController::onAbortProgressRequested(std::shared_ptr<Variable> variable)
452 void VariableController::onAbortProgressRequested(std::shared_ptr<Variable> variable)
453 {
453 {
454 qCDebug(LOG_VariableController()) << "TORM: variableController::onAbortProgressRequested"
454 qCDebug(LOG_VariableController()) << "TORM: variableController::onAbortProgressRequested"
455 << QThread::currentThread()->objectName() << variable->name();
455 << QThread::currentThread()->objectName() << variable->name();
456
456
457 auto itVar = impl->m_VariableToIdentifierMap.find(variable);
457 auto itVar = impl->m_VariableToIdentifierMap.find(variable);
458 if (itVar == impl->m_VariableToIdentifierMap.cend()) {
458 if (itVar == impl->m_VariableToIdentifierMap.cend()) {
459 qCCritical(LOG_VariableController())
459 qCCritical(LOG_VariableController())
460 << tr("Impossible to onAbortProgressRequested request for unknown variable");
460 << tr("Impossible to onAbortProgressRequested request for unknown variable");
461 return;
461 return;
462 }
462 }
463
463
464 auto varId = itVar->second;
464 auto varId = itVar->second;
465
465
466 auto itVarHandler = impl->m_VarIdToVarRequestHandler.find(varId);
466 auto itVarHandler = impl->m_VarIdToVarRequestHandler.find(varId);
467 if (itVarHandler == impl->m_VarIdToVarRequestHandler.cend()) {
467 if (itVarHandler == impl->m_VarIdToVarRequestHandler.cend()) {
468 qCCritical(LOG_VariableController())
468 qCCritical(LOG_VariableController())
469 << tr("Impossible to onAbortProgressRequested for variable with unknown handler");
469 << tr("Impossible to onAbortProgressRequested for variable with unknown handler");
470 return;
470 return;
471 }
471 }
472
472
473 auto varHandler = itVarHandler->second.get();
473 auto varHandler = itVarHandler->second.get();
474
474
475 // case where a variable has a running request
475 // case where a variable has a running request
476 if (varHandler->m_State != VariableRequestHandlerState::OFF) {
476 if (varHandler->m_State != VariableRequestHandlerState::OFF) {
477 impl->cancelVariableRequest(varHandler->m_RunningVarRequest.m_VariableGroupId);
477 impl->cancelVariableRequest(varHandler->m_RunningVarRequest.m_VariableGroupId);
478 }
478 }
479 }
479 }
480
480
481 void VariableController::onAbortAcquisitionRequested(QUuid vIdentifier)
481 void VariableController::onAbortAcquisitionRequested(QUuid vIdentifier)
482 {
482 {
483 qCDebug(LOG_VariableController()) << "TORM: variableController::onAbortAcquisitionRequested"
483 qCDebug(LOG_VariableController()) << "TORM: variableController::onAbortAcquisitionRequested"
484 << QThread::currentThread()->objectName() << vIdentifier;
484 << QThread::currentThread()->objectName() << vIdentifier;
485
485
486 if (auto var = impl->findVariable(vIdentifier)) {
486 if (auto var = impl->findVariable(vIdentifier)) {
487 this->onAbortProgressRequested(var);
487 this->onAbortProgressRequested(var);
488 }
488 }
489 else {
489 else {
490 qCCritical(LOG_VariableController())
490 qCCritical(LOG_VariableController())
491 << tr("Impossible to abort Acquisition Requestof a null variable");
491 << tr("Impossible to abort Acquisition Requestof a null variable");
492 }
492 }
493 }
493 }
494
494
495 void VariableController::onAddSynchronizationGroupId(QUuid synchronizationGroupId)
495 void VariableController::onAddSynchronizationGroupId(QUuid synchronizationGroupId)
496 {
496 {
497 qCDebug(LOG_VariableController()) << "TORM: VariableController::onAddSynchronizationGroupId"
497 qCDebug(LOG_VariableController()) << "TORM: VariableController::onAddSynchronizationGroupId"
498 << QThread::currentThread()->objectName()
498 << QThread::currentThread()->objectName()
499 << synchronizationGroupId;
499 << synchronizationGroupId;
500 auto vSynchroGroup = std::make_shared<VariableSynchronizationGroup>();
500 auto vSynchroGroup = std::make_shared<VariableSynchronizationGroup>();
501 impl->m_GroupIdToVariableSynchronizationGroupMap.insert(
501 impl->m_GroupIdToVariableSynchronizationGroupMap.insert(
502 std::make_pair(synchronizationGroupId, vSynchroGroup));
502 std::make_pair(synchronizationGroupId, vSynchroGroup));
503 }
503 }
504
504
505 void VariableController::onRemoveSynchronizationGroupId(QUuid synchronizationGroupId)
505 void VariableController::onRemoveSynchronizationGroupId(QUuid synchronizationGroupId)
506 {
506 {
507 impl->m_GroupIdToVariableSynchronizationGroupMap.erase(synchronizationGroupId);
507 impl->m_GroupIdToVariableSynchronizationGroupMap.erase(synchronizationGroupId);
508 }
508 }
509
509
510 void VariableController::onAddSynchronized(std::shared_ptr<Variable> variable,
510 void VariableController::onAddSynchronized(std::shared_ptr<Variable> variable,
511 QUuid synchronizationGroupId)
511 QUuid synchronizationGroupId)
512
512
513 {
513 {
514 qCDebug(LOG_VariableController()) << "TORM: VariableController::onAddSynchronized"
514 qCDebug(LOG_VariableController()) << "TORM: VariableController::onAddSynchronized"
515 << synchronizationGroupId;
515 << synchronizationGroupId;
516 auto varToVarIdIt = impl->m_VariableToIdentifierMap.find(variable);
516 auto varToVarIdIt = impl->m_VariableToIdentifierMap.find(variable);
517 if (varToVarIdIt != impl->m_VariableToIdentifierMap.cend()) {
517 if (varToVarIdIt != impl->m_VariableToIdentifierMap.cend()) {
518 auto groupIdToVSGIt
518 auto groupIdToVSGIt
519 = impl->m_GroupIdToVariableSynchronizationGroupMap.find(synchronizationGroupId);
519 = impl->m_GroupIdToVariableSynchronizationGroupMap.find(synchronizationGroupId);
520 if (groupIdToVSGIt != impl->m_GroupIdToVariableSynchronizationGroupMap.cend()) {
520 if (groupIdToVSGIt != impl->m_GroupIdToVariableSynchronizationGroupMap.cend()) {
521 impl->m_VariableIdGroupIdMap.insert(
521 impl->m_VariableIdGroupIdMap.insert(
522 std::make_pair(varToVarIdIt->second, synchronizationGroupId));
522 std::make_pair(varToVarIdIt->second, synchronizationGroupId));
523 groupIdToVSGIt->second->addVariableId(varToVarIdIt->second);
523 groupIdToVSGIt->second->addVariableId(varToVarIdIt->second);
524 }
524 }
525 else {
525 else {
526 qCCritical(LOG_VariableController())
526 qCCritical(LOG_VariableController())
527 << tr("Impossible to synchronize a variable with an unknown sycnhronization group")
527 << tr("Impossible to synchronize a variable with an unknown sycnhronization group")
528 << variable->name();
528 << variable->name();
529 }
529 }
530 }
530 }
531 else {
531 else {
532 qCCritical(LOG_VariableController())
532 qCCritical(LOG_VariableController())
533 << tr("Impossible to synchronize a variable with no identifier") << variable->name();
533 << tr("Impossible to synchronize a variable with no identifier") << variable->name();
534 }
534 }
535 }
535 }
536
536
537 void VariableController::desynchronize(std::shared_ptr<Variable> variable,
537 void VariableController::desynchronize(std::shared_ptr<Variable> variable,
538 QUuid synchronizationGroupId)
538 QUuid synchronizationGroupId)
539 {
539 {
540 // Gets variable id
540 // Gets variable id
541 auto variableIt = impl->m_VariableToIdentifierMap.find(variable);
541 auto variableIt = impl->m_VariableToIdentifierMap.find(variable);
542 if (variableIt == impl->m_VariableToIdentifierMap.cend()) {
542 if (variableIt == impl->m_VariableToIdentifierMap.cend()) {
543 qCCritical(LOG_VariableController())
543 qCCritical(LOG_VariableController())
544 << tr("Can't desynchronize variable %1: variable identifier not found")
544 << tr("Can't desynchronize variable %1: variable identifier not found")
545 .arg(variable->name());
545 .arg(variable->name());
546 return;
546 return;
547 }
547 }
548
548
549 impl->desynchronize(variableIt, synchronizationGroupId);
549 impl->desynchronize(variableIt, synchronizationGroupId);
550 }
550 }
551
551
552 void VariableController::onRequestDataLoading(QVector<std::shared_ptr<Variable> > variables,
552 void VariableController::onRequestDataLoading(QVector<std::shared_ptr<Variable> > variables,
553 const SqpRange &range, bool synchronise)
553 const SqpRange &range, bool synchronise)
554 {
554 {
555 // variables is assumed synchronized
555 // variables is assumed synchronized
556 // TODO: Asser variables synchronization
556 // TODO: Asser variables synchronization
557 // we want to load data of the variable for the dateTime.
557 // we want to load data of the variable for the dateTime.
558 if (variables.isEmpty()) {
558 if (variables.isEmpty()) {
559 return;
559 return;
560 }
560 }
561
561
562 auto varRequestId = QUuid::createUuid();
562 auto varRequestId = QUuid::createUuid();
563 qCDebug(LOG_VariableController()) << "VariableController::onRequestDataLoading"
563 qCDebug(LOG_VariableController()) << "VariableController::onRequestDataLoading"
564 << QThread::currentThread()->objectName() << varRequestId
564 << QThread::currentThread()->objectName() << varRequestId
565 << range << synchronise;
565 << range << synchronise;
566
566
567 if (!synchronise) {
567 if (!synchronise) {
568 auto varIds = std::list<QUuid>{};
568 auto varIds = std::list<QUuid>{};
569 for (const auto &var : variables) {
569 for (const auto &var : variables) {
570 auto vId = impl->m_VariableToIdentifierMap.at(var);
570 auto vId = impl->m_VariableToIdentifierMap.at(var);
571 varIds.push_back(vId);
571 varIds.push_back(vId);
572 }
572 }
573 impl->m_VarGroupIdToVarIds.insert(std::make_pair(varRequestId, varIds));
573 impl->m_VarGroupIdToVarIds.insert(std::make_pair(varRequestId, varIds));
574 for (const auto &var : variables) {
574 for (const auto &var : variables) {
575 qCDebug(LOG_VariableController()) << "processRequest for" << var->name() << varRequestId
575 qCDebug(LOG_VariableController()) << "onRequestDataLoading: for" << varRequestId
576 << varIds.size();
576 << varIds.size();
577 impl->processRequest(var, range, varRequestId);
577 impl->processRequest(var, range, varRequestId);
578 }
578 }
579 }
579 }
580 else {
580 else {
581 auto vId = impl->m_VariableToIdentifierMap.at(variables.first());
581 auto vId = impl->m_VariableToIdentifierMap.at(variables.first());
582 auto varIdToGroupIdIt = impl->m_VariableIdGroupIdMap.find(vId);
582 auto varIdToGroupIdIt = impl->m_VariableIdGroupIdMap.find(vId);
583 if (varIdToGroupIdIt != impl->m_VariableIdGroupIdMap.cend()) {
583 if (varIdToGroupIdIt != impl->m_VariableIdGroupIdMap.cend()) {
584 auto groupId = varIdToGroupIdIt->second;
584 auto groupId = varIdToGroupIdIt->second;
585
585
586 auto vSynchronizationGroup
586 auto vSynchronizationGroup
587 = impl->m_GroupIdToVariableSynchronizationGroupMap.at(groupId);
587 = impl->m_GroupIdToVariableSynchronizationGroupMap.at(groupId);
588 auto vSyncIds = vSynchronizationGroup->getIds();
588 auto vSyncIds = vSynchronizationGroup->getIds();
589
589
590 auto varIds = std::list<QUuid>{};
590 auto varIds = std::list<QUuid>{};
591 for (auto vId : vSyncIds) {
591 for (auto vId : vSyncIds) {
592 varIds.push_back(vId);
592 varIds.push_back(vId);
593 }
593 }
594 qCDebug(LOG_VariableController()) << "onRequestDataLoading sync: for" << varRequestId
595 << varIds.size();
594 impl->m_VarGroupIdToVarIds.insert(std::make_pair(varRequestId, varIds));
596 impl->m_VarGroupIdToVarIds.insert(std::make_pair(varRequestId, varIds));
595
597
596 for (auto vId : vSyncIds) {
598 for (auto vId : vSyncIds) {
597 auto var = impl->findVariable(vId);
599 auto var = impl->findVariable(vId);
598
600
599 // Don't process already processed var
601 // Don't process already processed var
600 if (var != nullptr) {
602 if (var != nullptr) {
601 qCDebug(LOG_VariableController()) << "processRequest synchro for" << var->name()
603 qCDebug(LOG_VariableController()) << "processRequest synchro for" << var->name()
602 << varRequestId;
604 << varRequestId;
603 auto vSyncRangeRequested
605 auto vSyncRangeRequested
604 = variables.contains(var)
606 = variables.contains(var)
605 ? range
607 ? range
606 : computeSynchroRangeRequested(var->range(), range,
608 : computeSynchroRangeRequested(var->range(), range,
607 variables.first()->range());
609 variables.first()->range());
608 qCDebug(LOG_VariableController()) << "synchro RR" << vSyncRangeRequested;
610 qCDebug(LOG_VariableController()) << "synchro RR" << vSyncRangeRequested;
609 impl->processRequest(var, vSyncRangeRequested, varRequestId);
611 impl->processRequest(var, vSyncRangeRequested, varRequestId);
610 }
612 }
611 else {
613 else {
612 qCCritical(LOG_VariableController())
614 qCCritical(LOG_VariableController())
613
615
614 << tr("Impossible to synchronize a null variable");
616 << tr("Impossible to synchronize a null variable");
615 }
617 }
616 }
618 }
617 }
619 }
618 }
620 }
619
621
620 impl->updateVariables(varRequestId);
622 impl->updateVariables(varRequestId);
621 }
623 }
622
624
623
625
624 void VariableController::initialize()
626 void VariableController::initialize()
625 {
627 {
626 qCDebug(LOG_VariableController()) << tr("VariableController init") << QThread::currentThread();
628 qCDebug(LOG_VariableController()) << tr("VariableController init") << QThread::currentThread();
627 impl->m_WorkingMutex.lock();
629 impl->m_WorkingMutex.lock();
628 qCDebug(LOG_VariableController()) << tr("VariableController init END");
630 qCDebug(LOG_VariableController()) << tr("VariableController init END");
629 }
631 }
630
632
631 void VariableController::finalize()
633 void VariableController::finalize()
632 {
634 {
633 impl->m_WorkingMutex.unlock();
635 impl->m_WorkingMutex.unlock();
634 }
636 }
635
637
636 void VariableController::waitForFinish()
638 void VariableController::waitForFinish()
637 {
639 {
638 QMutexLocker locker{&impl->m_WorkingMutex};
640 QMutexLocker locker{&impl->m_WorkingMutex};
639 }
641 }
640
642
641 AcquisitionZoomType VariableController::getZoomType(const SqpRange &range, const SqpRange &oldRange)
643 AcquisitionZoomType VariableController::getZoomType(const SqpRange &range, const SqpRange &oldRange)
642 {
644 {
643 // t1.m_TStart <= t2.m_TStart && t2.m_TEnd <= t1.m_TEnd
645 // t1.m_TStart <= t2.m_TStart && t2.m_TEnd <= t1.m_TEnd
644 auto zoomType = AcquisitionZoomType::Unknown;
646 auto zoomType = AcquisitionZoomType::Unknown;
645 if (range.m_TStart <= oldRange.m_TStart && oldRange.m_TEnd <= range.m_TEnd) {
647 if (range.m_TStart <= oldRange.m_TStart && oldRange.m_TEnd <= range.m_TEnd) {
646 qCDebug(LOG_VariableController()) << "zoomtype: ZoomOut";
648 qCDebug(LOG_VariableController()) << "zoomtype: ZoomOut";
647 zoomType = AcquisitionZoomType::ZoomOut;
649 zoomType = AcquisitionZoomType::ZoomOut;
648 }
650 }
649 else if (range.m_TStart > oldRange.m_TStart && range.m_TEnd > oldRange.m_TEnd) {
651 else if (range.m_TStart > oldRange.m_TStart && range.m_TEnd > oldRange.m_TEnd) {
650 qCDebug(LOG_VariableController()) << "zoomtype: PanRight";
652 qCDebug(LOG_VariableController()) << "zoomtype: PanRight";
651 zoomType = AcquisitionZoomType::PanRight;
653 zoomType = AcquisitionZoomType::PanRight;
652 }
654 }
653 else if (range.m_TStart < oldRange.m_TStart && range.m_TEnd < oldRange.m_TEnd) {
655 else if (range.m_TStart < oldRange.m_TStart && range.m_TEnd < oldRange.m_TEnd) {
654 qCDebug(LOG_VariableController()) << "zoomtype: PanLeft";
656 qCDebug(LOG_VariableController()) << "zoomtype: PanLeft";
655 zoomType = AcquisitionZoomType::PanLeft;
657 zoomType = AcquisitionZoomType::PanLeft;
656 }
658 }
657 else if (range.m_TStart >= oldRange.m_TStart && oldRange.m_TEnd >= range.m_TEnd) {
659 else if (range.m_TStart >= oldRange.m_TStart && oldRange.m_TEnd >= range.m_TEnd) {
658 qCDebug(LOG_VariableController()) << "zoomtype: ZoomIn";
660 qCDebug(LOG_VariableController()) << "zoomtype: ZoomIn";
659 zoomType = AcquisitionZoomType::ZoomIn;
661 zoomType = AcquisitionZoomType::ZoomIn;
660 }
662 }
661 else {
663 else {
662 qCDebug(LOG_VariableController()) << "getZoomType: Unknown type detected";
664 qCDebug(LOG_VariableController()) << "getZoomType: Unknown type detected";
663 }
665 }
664 return zoomType;
666 return zoomType;
665 }
667 }
666
668
667 void VariableController::VariableControllerPrivate::processRequest(std::shared_ptr<Variable> var,
669 void VariableController::VariableControllerPrivate::processRequest(std::shared_ptr<Variable> var,
668 const SqpRange &rangeRequested,
670 const SqpRange &rangeRequested,
669 QUuid varRequestId)
671 QUuid varRequestId)
670 {
672 {
671 auto itVar = m_VariableToIdentifierMap.find(var);
673 auto itVar = m_VariableToIdentifierMap.find(var);
672 if (itVar == m_VariableToIdentifierMap.cend()) {
674 if (itVar == m_VariableToIdentifierMap.cend()) {
673 qCCritical(LOG_VariableController())
675 qCCritical(LOG_VariableController())
674 << tr("Impossible to process request for unknown variable");
676 << tr("Impossible to process request for unknown variable");
675 return;
677 return;
676 }
678 }
677
679
678 auto varId = itVar->second;
680 auto varId = itVar->second;
679
681
680 auto itVarHandler = m_VarIdToVarRequestHandler.find(varId);
682 auto itVarHandler = m_VarIdToVarRequestHandler.find(varId);
681 if (itVarHandler == m_VarIdToVarRequestHandler.cend()) {
683 if (itVarHandler == m_VarIdToVarRequestHandler.cend()) {
682 qCCritical(LOG_VariableController())
684 qCCritical(LOG_VariableController())
683 << tr("Impossible to process request for variable with unknown handler");
685 << tr("Impossible to process request for variable with unknown handler");
684 return;
686 return;
685 }
687 }
686
688
687 auto oldRange = var->range();
689 auto oldRange = var->range();
688
690
689 auto varHandler = itVarHandler->second.get();
691 auto varHandler = itVarHandler->second.get();
690
692
691 if (varHandler->m_State != VariableRequestHandlerState::OFF) {
693 if (varHandler->m_State != VariableRequestHandlerState::OFF) {
692 oldRange = varHandler->m_RunningVarRequest.m_RangeRequested;
694 oldRange = varHandler->m_RunningVarRequest.m_RangeRequested;
693 }
695 }
694
696
695 auto varRequest = VariableRequest{};
697 auto varRequest = VariableRequest{};
696 varRequest.m_VariableGroupId = varRequestId;
698 varRequest.m_VariableGroupId = varRequestId;
697 auto varStrategyRangesRequested
699 auto varStrategyRangesRequested
698 = m_VariableCacheStrategy->computeRange(oldRange, rangeRequested);
700 = m_VariableCacheStrategy->computeRange(oldRange, rangeRequested);
699 varRequest.m_RangeRequested = varStrategyRangesRequested.first;
701 varRequest.m_RangeRequested = varStrategyRangesRequested.first;
700 varRequest.m_CacheRangeRequested = varStrategyRangesRequested.second;
702 varRequest.m_CacheRangeRequested = varStrategyRangesRequested.second;
701
703
702 switch (varHandler->m_State) {
704 switch (varHandler->m_State) {
703 case VariableRequestHandlerState::OFF: {
705 case VariableRequestHandlerState::OFF: {
704 qCDebug(LOG_VariableController()) << tr("Process Request OFF")
706 qCDebug(LOG_VariableController()) << tr("Process Request OFF")
705 << varRequest.m_RangeRequested
707 << varRequest.m_RangeRequested
706 << varRequest.m_CacheRangeRequested;
708 << varRequest.m_CacheRangeRequested;
707 varHandler->m_RunningVarRequest = varRequest;
709 varHandler->m_RunningVarRequest = varRequest;
708 varHandler->m_State = VariableRequestHandlerState::RUNNING;
710 varHandler->m_State = VariableRequestHandlerState::RUNNING;
709 executeVarRequest(var, varRequest);
711 executeVarRequest(var, varRequest);
710 break;
712 break;
711 }
713 }
712 case VariableRequestHandlerState::RUNNING: {
714 case VariableRequestHandlerState::RUNNING: {
713 qCDebug(LOG_VariableController()) << tr("Process Request RUNNING")
715 qCDebug(LOG_VariableController()) << tr("Process Request RUNNING")
714 << varRequest.m_RangeRequested
716 << varRequest.m_RangeRequested
715 << varRequest.m_CacheRangeRequested;
717 << varRequest.m_CacheRangeRequested;
716 varHandler->m_State = VariableRequestHandlerState::PENDING;
718 varHandler->m_State = VariableRequestHandlerState::PENDING;
717 varHandler->m_PendingVarRequest = varRequest;
719 varHandler->m_PendingVarRequest = varRequest;
718 break;
720 break;
719 }
721 }
720 case VariableRequestHandlerState::PENDING: {
722 case VariableRequestHandlerState::PENDING: {
721 qCDebug(LOG_VariableController()) << tr("Process Request PENDING")
723 qCDebug(LOG_VariableController()) << tr("Process Request PENDING")
722 << varRequest.m_RangeRequested
724 << varRequest.m_RangeRequested
723 << varRequest.m_CacheRangeRequested;
725 << varRequest.m_CacheRangeRequested;
724 auto variableGroupIdToCancel = varHandler->m_PendingVarRequest.m_VariableGroupId;
726 auto variableGroupIdToCancel = varHandler->m_PendingVarRequest.m_VariableGroupId;
725 cancelVariableRequest(variableGroupIdToCancel);
727 cancelVariableRequest(variableGroupIdToCancel);
726 // Cancel variable can make state downgrade
728 // Cancel variable can make state downgrade
727 varHandler->m_State = VariableRequestHandlerState::PENDING;
729 varHandler->m_State = VariableRequestHandlerState::PENDING;
728 varHandler->m_PendingVarRequest = varRequest;
730 varHandler->m_PendingVarRequest = varRequest;
729
731
730 break;
732 break;
731 }
733 }
732 default:
734 default:
733 qCCritical(LOG_VariableController())
735 qCCritical(LOG_VariableController())
734 << QObject::tr("Unknown VariableRequestHandlerState");
736 << QObject::tr("Unknown VariableRequestHandlerState");
735 }
737 }
736 }
738 }
737
739
738 std::shared_ptr<Variable>
740 std::shared_ptr<Variable>
739 VariableController::VariableControllerPrivate::findVariable(QUuid vIdentifier)
741 VariableController::VariableControllerPrivate::findVariable(QUuid vIdentifier)
740 {
742 {
741 std::shared_ptr<Variable> var;
743 std::shared_ptr<Variable> var;
742 auto findReply = [vIdentifier](const auto &entry) { return vIdentifier == entry.second; };
744 auto findReply = [vIdentifier](const auto &entry) { return vIdentifier == entry.second; };
743
745
744 auto end = m_VariableToIdentifierMap.cend();
746 auto end = m_VariableToIdentifierMap.cend();
745 auto it = std::find_if(m_VariableToIdentifierMap.cbegin(), end, findReply);
747 auto it = std::find_if(m_VariableToIdentifierMap.cbegin(), end, findReply);
746 if (it != end) {
748 if (it != end) {
747 var = it->first;
749 var = it->first;
748 }
750 }
749 else {
751 else {
750 qCCritical(LOG_VariableController())
752 qCCritical(LOG_VariableController())
751 << tr("Impossible to find the variable with the identifier: ") << vIdentifier;
753 << tr("Impossible to find the variable with the identifier: ") << vIdentifier;
752 }
754 }
753
755
754 return var;
756 return var;
755 }
757 }
756
758
757 std::shared_ptr<IDataSeries> VariableController::VariableControllerPrivate::retrieveDataSeries(
759 std::shared_ptr<IDataSeries> VariableController::VariableControllerPrivate::retrieveDataSeries(
758 const QVector<AcquisitionDataPacket> acqDataPacketVector)
760 const QVector<AcquisitionDataPacket> acqDataPacketVector)
759 {
761 {
760 qCDebug(LOG_VariableController()) << tr("TORM: retrieveDataSeries acqDataPacketVector size")
762 qCDebug(LOG_VariableController()) << tr("TORM: retrieveDataSeries acqDataPacketVector size")
761 << acqDataPacketVector.size();
763 << acqDataPacketVector.size();
762 std::shared_ptr<IDataSeries> dataSeries;
764 std::shared_ptr<IDataSeries> dataSeries;
763 if (!acqDataPacketVector.isEmpty()) {
765 if (!acqDataPacketVector.isEmpty()) {
764 dataSeries = acqDataPacketVector[0].m_DateSeries;
766 dataSeries = acqDataPacketVector[0].m_DateSeries;
765 for (int i = 1; i < acqDataPacketVector.size(); ++i) {
767 for (int i = 1; i < acqDataPacketVector.size(); ++i) {
766 dataSeries->merge(acqDataPacketVector[i].m_DateSeries.get());
768 dataSeries->merge(acqDataPacketVector[i].m_DateSeries.get());
767 }
769 }
768 }
770 }
769 qCDebug(LOG_VariableController()) << tr("TORM: retrieveDataSeries acqDataPacketVector size END")
771 qCDebug(LOG_VariableController()) << tr("TORM: retrieveDataSeries acqDataPacketVector size END")
770 << acqDataPacketVector.size();
772 << acqDataPacketVector.size();
771 return dataSeries;
773 return dataSeries;
772 }
774 }
773
775
774 void VariableController::VariableControllerPrivate::registerProvider(
776 void VariableController::VariableControllerPrivate::registerProvider(
775 std::shared_ptr<IDataProvider> provider)
777 std::shared_ptr<IDataProvider> provider)
776 {
778 {
777 if (m_ProviderSet.find(provider) == m_ProviderSet.end()) {
779 if (m_ProviderSet.find(provider) == m_ProviderSet.end()) {
778 qCDebug(LOG_VariableController()) << tr("Registering of a new provider")
780 qCDebug(LOG_VariableController()) << tr("Registering of a new provider")
779 << provider->objectName();
781 << provider->objectName();
780 m_ProviderSet.insert(provider);
782 m_ProviderSet.insert(provider);
781 connect(provider.get(), &IDataProvider::dataProvided, m_VariableAcquisitionWorker.get(),
783 connect(provider.get(), &IDataProvider::dataProvided, m_VariableAcquisitionWorker.get(),
782 &VariableAcquisitionWorker::onVariableDataAcquired);
784 &VariableAcquisitionWorker::onVariableDataAcquired);
783 connect(provider.get(), &IDataProvider::dataProvidedProgress,
785 connect(provider.get(), &IDataProvider::dataProvidedProgress,
784 m_VariableAcquisitionWorker.get(),
786 m_VariableAcquisitionWorker.get(),
785 &VariableAcquisitionWorker::onVariableRetrieveDataInProgress);
787 &VariableAcquisitionWorker::onVariableRetrieveDataInProgress);
786 connect(provider.get(), &IDataProvider::dataProvidedFailed,
788 connect(provider.get(), &IDataProvider::dataProvidedFailed,
787 m_VariableAcquisitionWorker.get(),
789 m_VariableAcquisitionWorker.get(),
788 &VariableAcquisitionWorker::onVariableAcquisitionFailed);
790 &VariableAcquisitionWorker::onVariableAcquisitionFailed);
789 }
791 }
790 else {
792 else {
791 qCDebug(LOG_VariableController()) << tr("Cannot register provider, it already exists ");
793 qCDebug(LOG_VariableController()) << tr("Cannot register provider, it already exists ");
792 }
794 }
793 }
795 }
794
796
795 QUuid VariableController::VariableControllerPrivate::acceptVariableRequest(
797 QUuid VariableController::VariableControllerPrivate::acceptVariableRequest(
796 QUuid varId, std::shared_ptr<IDataSeries> dataSeries)
798 QUuid varId, std::shared_ptr<IDataSeries> dataSeries)
797 {
799 {
798 auto itVarHandler = m_VarIdToVarRequestHandler.find(varId);
800 auto itVarHandler = m_VarIdToVarRequestHandler.find(varId);
799 if (itVarHandler == m_VarIdToVarRequestHandler.cend()) {
801 if (itVarHandler == m_VarIdToVarRequestHandler.cend()) {
800 return QUuid();
802 return QUuid();
801 }
803 }
802
804
803 auto varHandler = itVarHandler->second.get();
805 auto varHandler = itVarHandler->second.get();
804 if (varHandler->m_State == VariableRequestHandlerState::OFF) {
806 if (varHandler->m_State == VariableRequestHandlerState::OFF) {
805 qCCritical(LOG_VariableController())
807 qCCritical(LOG_VariableController())
806 << tr("acceptVariableRequest impossible on a variable with OFF state");
808 << tr("acceptVariableRequest impossible on a variable with OFF state");
807 }
809 }
808
810
809 varHandler->m_RunningVarRequest.m_DataSeries = dataSeries;
811 varHandler->m_RunningVarRequest.m_DataSeries = dataSeries;
810 varHandler->m_CanUpdate = true;
812 varHandler->m_CanUpdate = true;
811
813
812 // Element traitΓ©, on a dΓ©jΓ  toutes les donnΓ©es necessaires
814 // Element traitΓ©, on a dΓ©jΓ  toutes les donnΓ©es necessaires
813 auto varGroupId = varHandler->m_RunningVarRequest.m_VariableGroupId;
815 auto varGroupId = varHandler->m_RunningVarRequest.m_VariableGroupId;
814 qCDebug(LOG_VariableController()) << "Variable::acceptVariableRequest" << varGroupId
816 qCDebug(LOG_VariableController()) << "Variable::acceptVariableRequest" << varGroupId
815 << m_VarGroupIdToVarIds.size();
817 << m_VarGroupIdToVarIds.size();
816
818
817 return varHandler->m_RunningVarRequest.m_VariableGroupId;
819 return varHandler->m_RunningVarRequest.m_VariableGroupId;
818 }
820 }
819
821
820 void VariableController::VariableControllerPrivate::updateVariables(QUuid varRequestId)
822 void VariableController::VariableControllerPrivate::updateVariables(QUuid varRequestId)
821 {
823 {
822 qCDebug(LOG_VariableController()) << "VariableControllerPrivate::updateVariables"
824 qCDebug(LOG_VariableController()) << "VariableControllerPrivate::updateVariables"
823 << QThread::currentThread()->objectName() << varRequestId;
825 << QThread::currentThread()->objectName() << varRequestId;
824
826
825 auto varGroupIdToVarIdsIt = m_VarGroupIdToVarIds.find(varRequestId);
827 auto varGroupIdToVarIdsIt = m_VarGroupIdToVarIds.find(varRequestId);
826 if (varGroupIdToVarIdsIt == m_VarGroupIdToVarIds.end()) {
828 if (varGroupIdToVarIdsIt == m_VarGroupIdToVarIds.end()) {
827 qCWarning(LOG_VariableController())
829 qCWarning(LOG_VariableController())
828 << tr("Impossible to updateVariables of unknown variables") << varRequestId;
830 << tr("Impossible to updateVariables of unknown variables") << varRequestId;
829 return;
831 return;
830 }
832 }
831
833
832 auto &varIds = varGroupIdToVarIdsIt->second;
834 auto &varIds = varGroupIdToVarIdsIt->second;
833 auto varIdsEnd = varIds.end();
835 auto varIdsEnd = varIds.end();
834 bool processVariableUpdate = true;
836 bool processVariableUpdate = true;
835 qCDebug(LOG_VariableController()) << "VariableControllerPrivate::updateVariables"
836 << varRequestId << varIds.size();
837 for (auto varIdsIt = varIds.begin(); (varIdsIt != varIdsEnd) && processVariableUpdate;
837 for (auto varIdsIt = varIds.begin(); (varIdsIt != varIdsEnd) && processVariableUpdate;
838 ++varIdsIt) {
838 ++varIdsIt) {
839 auto itVarHandler = m_VarIdToVarRequestHandler.find(*varIdsIt);
839 auto itVarHandler = m_VarIdToVarRequestHandler.find(*varIdsIt);
840 if (itVarHandler != m_VarIdToVarRequestHandler.cend()) {
840 if (itVarHandler != m_VarIdToVarRequestHandler.cend()) {
841 processVariableUpdate &= itVarHandler->second->m_CanUpdate;
841 processVariableUpdate &= itVarHandler->second->m_CanUpdate;
842 }
842 }
843 }
843 }
844
844
845 if (processVariableUpdate) {
845 if (processVariableUpdate) {
846 qCDebug(LOG_VariableController()) << "Final update OK for the var request" << varIds.size();
847 for (auto varIdsIt = varIds.begin(); varIdsIt != varIdsEnd; ++varIdsIt) {
846 for (auto varIdsIt = varIds.begin(); varIdsIt != varIdsEnd; ++varIdsIt) {
848 auto itVarHandler = m_VarIdToVarRequestHandler.find(*varIdsIt);
847 auto itVarHandler = m_VarIdToVarRequestHandler.find(*varIdsIt);
849 if (itVarHandler != m_VarIdToVarRequestHandler.cend()) {
848 if (itVarHandler != m_VarIdToVarRequestHandler.cend()) {
850 if (auto var = findVariable(*varIdsIt)) {
849 if (auto var = findVariable(*varIdsIt)) {
851 auto &varRequest = itVarHandler->second->m_RunningVarRequest;
850 auto &varRequest = itVarHandler->second->m_RunningVarRequest;
852 var->setRange(varRequest.m_RangeRequested);
851 var->setRange(varRequest.m_RangeRequested);
853 var->setCacheRange(varRequest.m_CacheRangeRequested);
852 var->setCacheRange(varRequest.m_CacheRangeRequested);
854 qCDebug(LOG_VariableController()) << tr("1: onDataProvided")
853 qCDebug(LOG_VariableController()) << tr("1: onDataProvided")
855 << varRequest.m_RangeRequested
854 << varRequest.m_RangeRequested
856 << varRequest.m_CacheRangeRequested;
855 << varRequest.m_CacheRangeRequested;
857 qCDebug(LOG_VariableController()) << tr("2: onDataProvided var points before")
856 qCDebug(LOG_VariableController()) << tr("2: onDataProvided var points before")
858 << var->nbPoints()
857 << var->nbPoints()
859 << varRequest.m_DataSeries->nbPoints();
858 << varRequest.m_DataSeries->nbPoints();
860 var->mergeDataSeries(varRequest.m_DataSeries);
859 var->mergeDataSeries(varRequest.m_DataSeries);
861 qCDebug(LOG_VariableController()) << tr("3: onDataProvided var points after")
860 qCDebug(LOG_VariableController()) << tr("3: onDataProvided var points after")
862 << var->nbPoints();
861 << var->nbPoints();
863
862
864 emit var->updated();
863 emit var->updated();
865 qCDebug(LOG_VariableController()) << tr("Update OK");
866 }
864 }
867 else {
865 else {
868 qCCritical(LOG_VariableController())
866 qCCritical(LOG_VariableController())
869 << tr("Impossible to update data to a null variable");
867 << tr("Impossible to update data to a null variable");
870 }
868 }
871 }
869 }
872 }
870 }
873 updateVariableRequest(varRequestId);
871 updateVariableRequest(varRequestId);
874
872
875 // cleaning varRequestId
873 // cleaning varRequestId
876 qCDebug(LOG_VariableController()) << tr("m_VarGroupIdToVarIds erase") << varRequestId;
874 qCDebug(LOG_VariableController()) << tr("m_VarGroupIdToVarIds erase") << varRequestId;
877 m_VarGroupIdToVarIds.erase(varRequestId);
875 m_VarGroupIdToVarIds.erase(varRequestId);
878 if (m_VarGroupIdToVarIds.empty()) {
876 if (m_VarGroupIdToVarIds.empty()) {
879 emit q->acquisitionFinished();
877 emit q->acquisitionFinished();
880 }
878 }
881 }
879 }
882 }
880 }
883
881
884
882
885 void VariableController::VariableControllerPrivate::updateVariableRequest(QUuid varRequestId)
883 void VariableController::VariableControllerPrivate::updateVariableRequest(QUuid varRequestId)
886 {
884 {
887 auto varGroupIdToVarIdsIt = m_VarGroupIdToVarIds.find(varRequestId);
885 auto varGroupIdToVarIdsIt = m_VarGroupIdToVarIds.find(varRequestId);
888 if (varGroupIdToVarIdsIt == m_VarGroupIdToVarIds.end()) {
886 if (varGroupIdToVarIdsIt == m_VarGroupIdToVarIds.end()) {
889 qCCritical(LOG_VariableController()) << QObject::tr(
887 qCCritical(LOG_VariableController()) << QObject::tr(
890 "Impossible to updateVariableRequest since varGroupdId isn't here anymore");
888 "Impossible to updateVariableRequest since varGroupdId isn't here anymore");
891
889
892 return;
890 return;
893 }
891 }
894
892
895 auto &varIds = varGroupIdToVarIdsIt->second;
893 auto &varIds = varGroupIdToVarIdsIt->second;
896 auto varIdsEnd = varIds.end();
894 auto varIdsEnd = varIds.end();
895
896 // First pass all canUpdate of handler to false
897 for (auto varIdsIt = varIds.begin(); (varIdsIt != varIdsEnd); ++varIdsIt) {
897 for (auto varIdsIt = varIds.begin(); (varIdsIt != varIdsEnd); ++varIdsIt) {
898 auto itVarHandler = m_VarIdToVarRequestHandler.find(*varIdsIt);
898 auto itVarHandler = m_VarIdToVarRequestHandler.find(*varIdsIt);
899 if (itVarHandler != m_VarIdToVarRequestHandler.cend()) {
899 if (itVarHandler != m_VarIdToVarRequestHandler.cend()) {
900
900
901 auto varHandler = itVarHandler->second.get();
901 auto varHandler = itVarHandler->second.get();
902 varHandler->m_CanUpdate = false;
902 varHandler->m_CanUpdate = false;
903 }
904 }
905 // Second update requests of handler
906 for (auto varIdsIt = varIds.begin(); (varIdsIt != varIdsEnd); ++varIdsIt) {
907 auto itVarHandler = m_VarIdToVarRequestHandler.find(*varIdsIt);
908 if (itVarHandler != m_VarIdToVarRequestHandler.cend()) {
903
909
910 auto varHandler = itVarHandler->second.get();
904
911
905 switch (varHandler->m_State) {
912 switch (varHandler->m_State) {
906 case VariableRequestHandlerState::OFF: {
913 case VariableRequestHandlerState::OFF: {
907 qCCritical(LOG_VariableController())
914 qCCritical(LOG_VariableController())
908 << QObject::tr("Impossible to update a variable with handler in OFF state");
915 << QObject::tr("Impossible to update a variable with handler in OFF state");
909 } break;
916 } break;
910 case VariableRequestHandlerState::RUNNING: {
917 case VariableRequestHandlerState::RUNNING: {
911 varHandler->m_State = VariableRequestHandlerState::OFF;
918 varHandler->m_State = VariableRequestHandlerState::OFF;
912 varHandler->m_RunningVarRequest = VariableRequest{};
919 varHandler->m_RunningVarRequest = VariableRequest{};
913 break;
920 break;
914 }
921 }
915 case VariableRequestHandlerState::PENDING: {
922 case VariableRequestHandlerState::PENDING: {
916 varHandler->m_State = VariableRequestHandlerState::RUNNING;
923 varHandler->m_State = VariableRequestHandlerState::RUNNING;
917 varHandler->m_RunningVarRequest = varHandler->m_PendingVarRequest;
924 varHandler->m_RunningVarRequest = varHandler->m_PendingVarRequest;
918 varHandler->m_PendingVarRequest = VariableRequest{};
925 varHandler->m_PendingVarRequest = VariableRequest{};
919 auto var = findVariable(itVarHandler->first);
926 auto var = findVariable(itVarHandler->first);
920 executeVarRequest(var, varHandler->m_RunningVarRequest);
927 executeVarRequest(var, varHandler->m_RunningVarRequest);
921 updateVariables(varHandler->m_RunningVarRequest.m_VariableGroupId);
928 updateVariables(varHandler->m_RunningVarRequest.m_VariableGroupId);
922 break;
929 break;
923 }
930 }
924 default:
931 default:
925 qCCritical(LOG_VariableController())
932 qCCritical(LOG_VariableController())
926 << QObject::tr("Unknown VariableRequestHandlerState");
933 << QObject::tr("Unknown VariableRequestHandlerState");
927 }
934 }
928 }
935 }
929 }
936 }
930 }
937 }
931
938
932
939
933 void VariableController::VariableControllerPrivate::cancelVariableRequest(QUuid varRequestId)
940 void VariableController::VariableControllerPrivate::cancelVariableRequest(QUuid varRequestId)
934 {
941 {
935 qCDebug(LOG_VariableController()) << tr("cancelVariableRequest") << varRequestId;
942 qCDebug(LOG_VariableController()) << tr("cancelVariableRequest") << varRequestId;
936
943
937 auto varGroupIdToVarIdsIt = m_VarGroupIdToVarIds.find(varRequestId);
944 auto varGroupIdToVarIdsIt = m_VarGroupIdToVarIds.find(varRequestId);
938 if (varGroupIdToVarIdsIt == m_VarGroupIdToVarIds.end()) {
945 if (varGroupIdToVarIdsIt == m_VarGroupIdToVarIds.end()) {
939 qCCritical(LOG_VariableController())
946 qCCritical(LOG_VariableController())
940 << tr("Impossible to cancelVariableRequest for unknown varGroupdId") << varRequestId;
947 << tr("Impossible to cancelVariableRequest for unknown varGroupdId") << varRequestId;
941 return;
948 return;
942 }
949 }
943
950
944 auto &varIds = varGroupIdToVarIdsIt->second;
951 auto &varIds = varGroupIdToVarIdsIt->second;
945 auto varIdsEnd = varIds.end();
952 auto varIdsEnd = varIds.end();
946 for (auto varIdsIt = varIds.begin(); (varIdsIt != varIdsEnd); ++varIdsIt) {
953 for (auto varIdsIt = varIds.begin(); (varIdsIt != varIdsEnd); ++varIdsIt) {
947 auto itVarHandler = m_VarIdToVarRequestHandler.find(*varIdsIt);
954 auto itVarHandler = m_VarIdToVarRequestHandler.find(*varIdsIt);
948 if (itVarHandler != m_VarIdToVarRequestHandler.cend()) {
955 if (itVarHandler != m_VarIdToVarRequestHandler.cend()) {
949
956
950 auto varHandler = itVarHandler->second.get();
957 auto varHandler = itVarHandler->second.get();
951 varHandler->m_VarId = QUuid{};
958 varHandler->m_VarId = QUuid{};
952 switch (varHandler->m_State) {
959 switch (varHandler->m_State) {
953 case VariableRequestHandlerState::OFF: {
960 case VariableRequestHandlerState::OFF: {
954 qCWarning(LOG_VariableController())
961 qCWarning(LOG_VariableController())
955 << QObject::tr("Impossible to cancel a variable with no running request");
962 << QObject::tr("Impossible to cancel a variable with no running request");
956 break;
963 break;
957 }
964 }
958 case VariableRequestHandlerState::RUNNING: {
965 case VariableRequestHandlerState::RUNNING: {
959
966
960 if (varHandler->m_RunningVarRequest.m_VariableGroupId == varRequestId) {
967 if (varHandler->m_RunningVarRequest.m_VariableGroupId == varRequestId) {
961 auto var = findVariable(itVarHandler->first);
968 auto var = findVariable(itVarHandler->first);
962 auto varProvider = m_VariableToProviderMap.at(var);
969 auto varProvider = m_VariableToProviderMap.at(var);
963 if (varProvider != nullptr) {
970 if (varProvider != nullptr) {
964 m_VariableAcquisitionWorker->abortProgressRequested(
971 m_VariableAcquisitionWorker->abortProgressRequested(
965 itVarHandler->first);
972 itVarHandler->first);
966 }
973 }
967 m_VariableModel->setDataProgress(var, 0.0);
974 m_VariableModel->setDataProgress(var, 0.0);
968 varHandler->m_CanUpdate = false;
975 varHandler->m_CanUpdate = false;
969 varHandler->m_State = VariableRequestHandlerState::OFF;
976 varHandler->m_State = VariableRequestHandlerState::OFF;
970 varHandler->m_RunningVarRequest = VariableRequest{};
977 varHandler->m_RunningVarRequest = VariableRequest{};
971 }
978 }
972 else {
979 else {
973 // TODO: log Impossible to cancel the running variable request beacause its
980 // TODO: log Impossible to cancel the running variable request beacause its
974 // varRequestId isn't not the canceled one
981 // varRequestId isn't not the canceled one
975 }
982 }
976 break;
983 break;
977 }
984 }
978 case VariableRequestHandlerState::PENDING: {
985 case VariableRequestHandlerState::PENDING: {
979 if (varHandler->m_RunningVarRequest.m_VariableGroupId == varRequestId) {
986 if (varHandler->m_RunningVarRequest.m_VariableGroupId == varRequestId) {
980 auto var = findVariable(itVarHandler->first);
987 auto var = findVariable(itVarHandler->first);
981 auto varProvider = m_VariableToProviderMap.at(var);
988 auto varProvider = m_VariableToProviderMap.at(var);
982 if (varProvider != nullptr) {
989 if (varProvider != nullptr) {
983 m_VariableAcquisitionWorker->abortProgressRequested(
990 m_VariableAcquisitionWorker->abortProgressRequested(
984 itVarHandler->first);
991 itVarHandler->first);
985 }
992 }
986 m_VariableModel->setDataProgress(var, 0.0);
993 m_VariableModel->setDataProgress(var, 0.0);
987 varHandler->m_CanUpdate = false;
994 varHandler->m_CanUpdate = false;
988 varHandler->m_State = VariableRequestHandlerState::RUNNING;
995 varHandler->m_State = VariableRequestHandlerState::RUNNING;
989 varHandler->m_RunningVarRequest = varHandler->m_PendingVarRequest;
996 varHandler->m_RunningVarRequest = varHandler->m_PendingVarRequest;
990 varHandler->m_PendingVarRequest = VariableRequest{};
997 varHandler->m_PendingVarRequest = VariableRequest{};
991 executeVarRequest(var, varHandler->m_RunningVarRequest);
998 executeVarRequest(var, varHandler->m_RunningVarRequest);
992 }
999 }
993 else if (varHandler->m_PendingVarRequest.m_VariableGroupId == varRequestId) {
1000 else if (varHandler->m_PendingVarRequest.m_VariableGroupId == varRequestId) {
994 varHandler->m_State = VariableRequestHandlerState::RUNNING;
1001 varHandler->m_State = VariableRequestHandlerState::RUNNING;
995 varHandler->m_PendingVarRequest = VariableRequest{};
1002 varHandler->m_PendingVarRequest = VariableRequest{};
996 }
1003 }
997 else {
1004 else {
998 // TODO: log Impossible to cancel the variable request beacause its
1005 // TODO: log Impossible to cancel the variable request beacause its
999 // varRequestId isn't not the canceled one
1006 // varRequestId isn't not the canceled one
1000 }
1007 }
1001 break;
1008 break;
1002 }
1009 }
1003 default:
1010 default:
1004 qCCritical(LOG_VariableController())
1011 qCCritical(LOG_VariableController())
1005 << QObject::tr("Unknown VariableRequestHandlerState");
1012 << QObject::tr("Unknown VariableRequestHandlerState");
1006 }
1013 }
1007 }
1014 }
1008 }
1015 }
1009 qCDebug(LOG_VariableController()) << tr("cancelVariableRequest: erase") << varRequestId;
1016 qCDebug(LOG_VariableController()) << tr("cancelVariableRequest: erase") << varRequestId;
1010 m_VarGroupIdToVarIds.erase(varRequestId);
1017 m_VarGroupIdToVarIds.erase(varRequestId);
1011 if (m_VarGroupIdToVarIds.empty()) {
1018 if (m_VarGroupIdToVarIds.empty()) {
1012 emit q->acquisitionFinished();
1019 emit q->acquisitionFinished();
1013 }
1020 }
1014 }
1021 }
1015
1022
1016 void VariableController::VariableControllerPrivate::executeVarRequest(std::shared_ptr<Variable> var,
1023 void VariableController::VariableControllerPrivate::executeVarRequest(std::shared_ptr<Variable> var,
1017 VariableRequest &varRequest)
1024 VariableRequest &varRequest)
1018 {
1025 {
1019 qCDebug(LOG_VariableController()) << tr("TORM: executeVarRequest");
1020
1021 auto varIdIt = m_VariableToIdentifierMap.find(var);
1026 auto varIdIt = m_VariableToIdentifierMap.find(var);
1022 if (varIdIt == m_VariableToIdentifierMap.cend()) {
1027 if (varIdIt == m_VariableToIdentifierMap.cend()) {
1023 qCWarning(LOG_VariableController()) << tr(
1028 qCWarning(LOG_VariableController()) << tr(
1024 "Can't execute request of a variable that is not registered (may has been deleted)");
1029 "Can't execute request of a variable that is not registered (may has been deleted)");
1025 return;
1030 return;
1026 }
1031 }
1027
1032
1028 auto varId = varIdIt->second;
1033 auto varId = varIdIt->second;
1029
1034
1030 auto varCacheRange = var->cacheRange();
1035 auto varCacheRange = var->cacheRange();
1031 auto varCacheRangeRequested = varRequest.m_CacheRangeRequested;
1036 auto varCacheRangeRequested = varRequest.m_CacheRangeRequested;
1032 auto notInCacheRangeList
1037 auto notInCacheRangeList
1033 = Variable::provideNotInCacheRangeList(varCacheRange, varCacheRangeRequested);
1038 = Variable::provideNotInCacheRangeList(varCacheRange, varCacheRangeRequested);
1034 auto inCacheRangeList
1039 auto inCacheRangeList
1035 = Variable::provideInCacheRangeList(varCacheRange, varCacheRangeRequested);
1040 = Variable::provideInCacheRangeList(varCacheRange, varCacheRangeRequested);
1036
1041
1037 if (!notInCacheRangeList.empty()) {
1042 if (!notInCacheRangeList.empty()) {
1038
1043
1039 auto varProvider = m_VariableToProviderMap.at(var);
1044 auto varProvider = m_VariableToProviderMap.at(var);
1040 if (varProvider != nullptr) {
1045 if (varProvider != nullptr) {
1041 qCDebug(LOG_VariableController()) << "executeVarRequest " << varRequest.m_RangeRequested
1046 qCDebug(LOG_VariableController()) << "executeVarRequest " << varRequest.m_RangeRequested
1042 << varRequest.m_CacheRangeRequested;
1047 << varRequest.m_CacheRangeRequested;
1043 m_VariableAcquisitionWorker->pushVariableRequest(
1048 m_VariableAcquisitionWorker->pushVariableRequest(
1044 varRequest.m_VariableGroupId, varId,
1049 varRequest.m_VariableGroupId, varId,
1045 DataProviderParameters{std::move(notInCacheRangeList), var->metadata()},
1050 DataProviderParameters{std::move(notInCacheRangeList), var->metadata()},
1046 varProvider);
1051 varProvider);
1047 }
1052 }
1048 else {
1053 else {
1049 qCCritical(LOG_VariableController())
1054 qCCritical(LOG_VariableController())
1050 << "Impossible to provide data with a null provider";
1055 << "Impossible to provide data with a null provider";
1051 }
1056 }
1052
1057
1053 if (!inCacheRangeList.empty()) {
1058 if (!inCacheRangeList.empty()) {
1054 emit q->updateVarDisplaying(var, inCacheRangeList.first());
1059 emit q->updateVarDisplaying(var, inCacheRangeList.first());
1055 }
1060 }
1056 }
1061 }
1057 else {
1062 else {
1063 qCDebug(LOG_VariableController()) << "All already in the cache "
1064 << varRequest.m_RangeRequested;
1058 acceptVariableRequest(varId,
1065 acceptVariableRequest(varId,
1059 var->dataSeries()->subDataSeries(varRequest.m_CacheRangeRequested));
1066 var->dataSeries()->subDataSeries(varRequest.m_CacheRangeRequested));
1060 }
1067 }
1061 }
1068 }
1062
1069
1063 template <typename VariableIterator>
1070 template <typename VariableIterator>
1064 void VariableController::VariableControllerPrivate::desynchronize(VariableIterator variableIt,
1071 void VariableController::VariableControllerPrivate::desynchronize(VariableIterator variableIt,
1065 const QUuid &syncGroupId)
1072 const QUuid &syncGroupId)
1066 {
1073 {
1067 const auto &variable = variableIt->first;
1074 const auto &variable = variableIt->first;
1068 const auto &variableId = variableIt->second;
1075 const auto &variableId = variableIt->second;
1069
1076
1070 // Gets synchronization group
1077 // Gets synchronization group
1071 auto groupIt = m_GroupIdToVariableSynchronizationGroupMap.find(syncGroupId);
1078 auto groupIt = m_GroupIdToVariableSynchronizationGroupMap.find(syncGroupId);
1072 if (groupIt == m_GroupIdToVariableSynchronizationGroupMap.cend()) {
1079 if (groupIt == m_GroupIdToVariableSynchronizationGroupMap.cend()) {
1073 qCCritical(LOG_VariableController())
1080 qCCritical(LOG_VariableController())
1074 << tr("Can't desynchronize variable %1: unknown synchronization group")
1081 << tr("Can't desynchronize variable %1: unknown synchronization group")
1075 .arg(variable->name());
1082 .arg(variable->name());
1076 return;
1083 return;
1077 }
1084 }
1078
1085
1079 // Removes variable from synchronization group
1086 // Removes variable from synchronization group
1080 auto synchronizationGroup = groupIt->second;
1087 auto synchronizationGroup = groupIt->second;
1081 synchronizationGroup->removeVariableId(variableId);
1088 synchronizationGroup->removeVariableId(variableId);
1082
1089
1083 // Removes link between variable and synchronization group
1090 // Removes link between variable and synchronization group
1084 m_VariableIdGroupIdMap.erase(variableId);
1091 m_VariableIdGroupIdMap.erase(variableId);
1085 }
1092 }
1 NO CONTENT: modified file
NO CONTENT: modified file
@@ -1,274 +1,275
1 #include "AmdaProvider.h"
1 #include "AmdaProvider.h"
2 #include "AmdaDefs.h"
2 #include "AmdaDefs.h"
3 #include "AmdaResultParser.h"
3 #include "AmdaResultParser.h"
4 #include "AmdaServer.h"
4 #include "AmdaServer.h"
5
5
6 #include <Common/DateUtils.h>
6 #include <Common/DateUtils.h>
7 #include <Data/DataProviderParameters.h>
7 #include <Data/DataProviderParameters.h>
8 #include <Network/NetworkController.h>
8 #include <Network/NetworkController.h>
9 #include <SqpApplication.h>
9 #include <SqpApplication.h>
10 #include <Variable/Variable.h>
10 #include <Variable/Variable.h>
11
11
12 #include <QNetworkAccessManager>
12 #include <QNetworkAccessManager>
13 #include <QNetworkReply>
13 #include <QNetworkReply>
14 #include <QTemporaryFile>
14 #include <QTemporaryFile>
15 #include <QThread>
15 #include <QThread>
16
16
17 Q_LOGGING_CATEGORY(LOG_AmdaProvider, "AmdaProvider")
17 Q_LOGGING_CATEGORY(LOG_AmdaProvider, "AmdaProvider")
18
18
19 namespace {
19 namespace {
20
20
21 /// URL format for a request on AMDA server. The parameters are as follows:
21 /// URL format for a request on AMDA server. The parameters are as follows:
22 /// - %1: server URL
22 /// - %1: server URL
23 /// - %2: start date
23 /// - %2: start date
24 /// - %3: end date
24 /// - %3: end date
25 /// - %4: parameter id
25 /// - %4: parameter id
26 /// AMDA V2: http://amdatest.irap.omp.eu/php/rest/
26 /// AMDA V2: http://amdatest.irap.omp.eu/php/rest/
27 const auto AMDA_URL_FORMAT = QStringLiteral(
27 const auto AMDA_URL_FORMAT = QStringLiteral(
28 "http://%1/php/rest/"
28 "http://%1/php/rest/"
29 "getParameter.php?startTime=%2&stopTime=%3&parameterID=%4&outputFormat=ASCII&"
29 "getParameter.php?startTime=%2&stopTime=%3&parameterID=%4&outputFormat=ASCII&"
30 "timeFormat=ISO8601&gzip=0");
30 "timeFormat=ISO8601&gzip=0");
31
31
32 /// Dates format passed in the URL (e.g 2013-09-23T09:00)
32 /// Dates format passed in the URL (e.g 2013-09-23T09:00)
33 const auto AMDA_TIME_FORMAT = QStringLiteral("yyyy-MM-ddThh:mm:ss");
33 const auto AMDA_TIME_FORMAT = QStringLiteral("yyyy-MM-ddThh:mm:ss");
34
34
35 /// Formats a time to a date that can be passed in URL
35 /// Formats a time to a date that can be passed in URL
36 QString dateFormat(double sqpRange) noexcept
36 QString dateFormat(double sqpRange) noexcept
37 {
37 {
38 auto dateTime = DateUtils::dateTime(sqpRange);
38 auto dateTime = DateUtils::dateTime(sqpRange);
39 return dateTime.toString(AMDA_TIME_FORMAT);
39 return dateTime.toString(AMDA_TIME_FORMAT);
40 }
40 }
41
41
42
42
43 } // namespace
43 } // namespace
44
44
45 AmdaProvider::AmdaProvider()
45 AmdaProvider::AmdaProvider()
46 {
46 {
47 qCDebug(LOG_AmdaProvider()) << tr("AmdaProvider::AmdaProvider") << QThread::currentThread();
47 qCDebug(LOG_AmdaProvider()) << tr("AmdaProvider::AmdaProvider") << QThread::currentThread();
48 if (auto app = sqpApp) {
48 if (auto app = sqpApp) {
49 auto &networkController = app->networkController();
49 auto &networkController = app->networkController();
50 connect(this, SIGNAL(requestConstructed(std::shared_ptr<QNetworkRequest>, QUuid,
50 connect(this, SIGNAL(requestConstructed(std::shared_ptr<QNetworkRequest>, QUuid,
51 std::function<void(QNetworkReply *, QUuid)>)),
51 std::function<void(QNetworkReply *, QUuid)>)),
52 &networkController,
52 &networkController,
53 SLOT(onProcessRequested(std::shared_ptr<QNetworkRequest>, QUuid,
53 SLOT(onProcessRequested(std::shared_ptr<QNetworkRequest>, QUuid,
54 std::function<void(QNetworkReply *, QUuid)>)));
54 std::function<void(QNetworkReply *, QUuid)>)));
55
55
56
56
57 connect(&sqpApp->networkController(),
57 connect(&sqpApp->networkController(),
58 SIGNAL(replyDownloadProgress(QUuid, std::shared_ptr<QNetworkRequest>, double)),
58 SIGNAL(replyDownloadProgress(QUuid, std::shared_ptr<QNetworkRequest>, double)),
59 this,
59 this,
60 SLOT(onReplyDownloadProgress(QUuid, std::shared_ptr<QNetworkRequest>, double)));
60 SLOT(onReplyDownloadProgress(QUuid, std::shared_ptr<QNetworkRequest>, double)));
61 }
61 }
62 }
62 }
63
63
64 std::shared_ptr<IDataProvider> AmdaProvider::clone() const
64 std::shared_ptr<IDataProvider> AmdaProvider::clone() const
65 {
65 {
66 // No copy is made in the clone
66 // No copy is made in the clone
67 return std::make_shared<AmdaProvider>();
67 return std::make_shared<AmdaProvider>();
68 }
68 }
69
69
70 void AmdaProvider::requestDataLoading(QUuid acqIdentifier, const DataProviderParameters &parameters)
70 void AmdaProvider::requestDataLoading(QUuid acqIdentifier, const DataProviderParameters &parameters)
71 {
71 {
72 // NOTE: Try to use multithread if possible
72 // NOTE: Try to use multithread if possible
73 const auto times = parameters.m_Times;
73 const auto times = parameters.m_Times;
74 const auto data = parameters.m_Data;
74 const auto data = parameters.m_Data;
75 for (const auto &dateTime : qAsConst(times)) {
75 for (const auto &dateTime : qAsConst(times)) {
76 qCDebug(LOG_AmdaProvider()) << tr("TORM AmdaProvider::requestDataLoading ") << acqIdentifier
76 qCDebug(LOG_AmdaProvider()) << tr("TORM AmdaProvider::requestDataLoading ") << acqIdentifier
77 << dateTime;
77 << dateTime;
78 this->retrieveData(acqIdentifier, dateTime, data);
78 this->retrieveData(acqIdentifier, dateTime, data);
79
79
80
80
81 // TORM when AMDA will support quick asynchrone request
81 // TORM when AMDA will support quick asynchrone request
82 QThread::msleep(1000);
82 QThread::msleep(1000);
83 }
83 }
84 }
84 }
85
85
86 void AmdaProvider::requestDataAborting(QUuid acqIdentifier)
86 void AmdaProvider::requestDataAborting(QUuid acqIdentifier)
87 {
87 {
88 if (auto app = sqpApp) {
88 if (auto app = sqpApp) {
89 auto &networkController = app->networkController();
89 auto &networkController = app->networkController();
90 networkController.onReplyCanceled(acqIdentifier);
90 networkController.onReplyCanceled(acqIdentifier);
91 }
91 }
92 }
92 }
93
93
94 void AmdaProvider::onReplyDownloadProgress(QUuid acqIdentifier,
94 void AmdaProvider::onReplyDownloadProgress(QUuid acqIdentifier,
95 std::shared_ptr<QNetworkRequest> networkRequest,
95 std::shared_ptr<QNetworkRequest> networkRequest,
96 double progress)
96 double progress)
97 {
97 {
98 qCDebug(LOG_AmdaProvider()) << tr("onReplyDownloadProgress") << acqIdentifier
98 qCDebug(LOG_AmdaProvider()) << tr("onReplyDownloadProgress") << acqIdentifier
99 << networkRequest.get() << progress;
99 << networkRequest.get() << progress;
100 auto acqIdToRequestProgressMapIt = m_AcqIdToRequestProgressMap.find(acqIdentifier);
100 auto acqIdToRequestProgressMapIt = m_AcqIdToRequestProgressMap.find(acqIdentifier);
101 if (acqIdToRequestProgressMapIt != m_AcqIdToRequestProgressMap.end()) {
101 if (acqIdToRequestProgressMapIt != m_AcqIdToRequestProgressMap.end()) {
102
102
103 // Update the progression for the current request
103 // Update the progression for the current request
104 auto requestPtr = networkRequest;
104 auto requestPtr = networkRequest;
105 auto findRequest = [requestPtr](const auto &entry) { return requestPtr == entry.first; };
105 auto findRequest = [requestPtr](const auto &entry) { return requestPtr == entry.first; };
106
106
107 auto &requestProgressMap = acqIdToRequestProgressMapIt->second;
107 auto &requestProgressMap = acqIdToRequestProgressMapIt->second;
108 auto requestProgressMapEnd = requestProgressMap.end();
108 auto requestProgressMapEnd = requestProgressMap.end();
109 auto requestProgressMapIt
109 auto requestProgressMapIt
110 = std::find_if(requestProgressMap.begin(), requestProgressMapEnd, findRequest);
110 = std::find_if(requestProgressMap.begin(), requestProgressMapEnd, findRequest);
111
111
112 if (requestProgressMapIt != requestProgressMapEnd) {
112 if (requestProgressMapIt != requestProgressMapEnd) {
113 requestProgressMapIt->second = progress;
113 requestProgressMapIt->second = progress;
114 }
114 }
115 else {
115 else {
116 // This case can happened when a progression is send after the request has been
116 // This case can happened when a progression is send after the request has been
117 // finished.
117 // finished.
118 // Generaly the case when aborting a request
118 // Generaly the case when aborting a request
119 qCDebug(LOG_AmdaProvider()) << tr("Can't retrieve Request in progress") << acqIdentifier
119 qCDebug(LOG_AmdaProvider()) << tr("Can't retrieve Request in progress") << acqIdentifier
120 << networkRequest.get() << progress;
120 << networkRequest.get() << progress;
121 }
121 }
122
122
123 // Compute the current final progress and notify it
123 // Compute the current final progress and notify it
124 double finalProgress = 0.0;
124 double finalProgress = 0.0;
125
125
126 auto fraq = requestProgressMap.size();
126 auto fraq = requestProgressMap.size();
127
127
128 for (auto requestProgress : requestProgressMap) {
128 for (auto requestProgress : requestProgressMap) {
129 finalProgress += requestProgress.second;
129 finalProgress += requestProgress.second;
130 qCDebug(LOG_AmdaProvider()) << tr("Current final progress without fraq:")
130 qCDebug(LOG_AmdaProvider()) << tr("Current final progress without fraq:")
131 << finalProgress << requestProgress.second;
131 << finalProgress << requestProgress.second;
132 }
132 }
133
133
134 if (fraq > 0) {
134 if (fraq > 0) {
135 finalProgress = finalProgress / fraq;
135 finalProgress = finalProgress / fraq;
136 }
136 }
137
137
138 qCDebug(LOG_AmdaProvider()) << tr("Current final progress: ") << fraq << finalProgress;
138 qCDebug(LOG_AmdaProvider()) << tr("final progress: ")
139 << QThread::currentThread()->objectName() << acqIdentifier
140 << fraq << finalProgress;
139 emit dataProvidedProgress(acqIdentifier, finalProgress);
141 emit dataProvidedProgress(acqIdentifier, finalProgress);
140 }
142 }
141 else {
143 else {
142 // This case can happened when a progression is send after the request has been finished.
144 // This case can happened when a progression is send after the request has been finished.
143 // Generaly the case when aborting a request
145 // Generaly the case when aborting a request
146 qCDebug(LOG_AmdaProvider()) << tr("Acquisition request not found: final progress: 100 : ")
147 << QThread::currentThread()->objectName() << acqIdentifier;
144 emit dataProvidedProgress(acqIdentifier, 100.0);
148 emit dataProvidedProgress(acqIdentifier, 100.0);
145 }
149 }
146 }
150 }
147
151
148 void AmdaProvider::retrieveData(QUuid token, const SqpRange &dateTime, const QVariantHash &data)
152 void AmdaProvider::retrieveData(QUuid token, const SqpRange &dateTime, const QVariantHash &data)
149 {
153 {
150 // Retrieves product ID from data: if the value is invalid, no request is made
154 // Retrieves product ID from data: if the value is invalid, no request is made
151 auto productId = data.value(AMDA_XML_ID_KEY).toString();
155 auto productId = data.value(AMDA_XML_ID_KEY).toString();
152 if (productId.isNull()) {
156 if (productId.isNull()) {
153 qCCritical(LOG_AmdaProvider()) << tr("Can't retrieve data: unknown product id");
157 qCCritical(LOG_AmdaProvider()) << tr("Can't retrieve data: unknown product id");
154 return;
158 return;
155 }
159 }
156
160
157 // Retrieves the data type that determines whether the expected format for the result file is
161 // Retrieves the data type that determines whether the expected format for the result file is
158 // scalar, vector...
162 // scalar, vector...
159 auto productValueType
163 auto productValueType
160 = DataSeriesTypeUtils::fromString(data.value(AMDA_DATA_TYPE_KEY).toString());
164 = DataSeriesTypeUtils::fromString(data.value(AMDA_DATA_TYPE_KEY).toString());
161
165
162 // /////////// //
166 // /////////// //
163 // Creates URL //
167 // Creates URL //
164 // /////////// //
168 // /////////// //
165
169
166 auto startDate = dateFormat(dateTime.m_TStart);
170 auto startDate = dateFormat(dateTime.m_TStart);
167 auto endDate = dateFormat(dateTime.m_TEnd);
171 auto endDate = dateFormat(dateTime.m_TEnd);
168
172
169 QVariantHash urlProperties{{AMDA_SERVER_KEY, data.value(AMDA_SERVER_KEY)}};
173 QVariantHash urlProperties{{AMDA_SERVER_KEY, data.value(AMDA_SERVER_KEY)}};
170 auto url = QUrl{QString{AMDA_URL_FORMAT}.arg(AmdaServer::instance().url(urlProperties),
174 auto url = QUrl{QString{AMDA_URL_FORMAT}.arg(AmdaServer::instance().url(urlProperties),
171 startDate, endDate, productId)};
175 startDate, endDate, productId)};
172 qCInfo(LOG_AmdaProvider()) << tr("TORM AmdaProvider::retrieveData url:") << url;
173 auto tempFile = std::make_shared<QTemporaryFile>();
176 auto tempFile = std::make_shared<QTemporaryFile>();
174
177
175 // LAMBDA
178 // LAMBDA
176 auto httpDownloadFinished = [this, dateTime, tempFile,
179 auto httpDownloadFinished = [this, dateTime, tempFile,
177 productValueType](QNetworkReply *reply, QUuid dataId) noexcept {
180 productValueType](QNetworkReply *reply, QUuid dataId) noexcept {
178
181
179 // Don't do anything if the reply was abort
182 // Don't do anything if the reply was abort
180 if (reply->error() == QNetworkReply::NoError) {
183 if (reply->error() == QNetworkReply::NoError) {
181
184
182 if (tempFile) {
185 if (tempFile) {
183 auto replyReadAll = reply->readAll();
186 auto replyReadAll = reply->readAll();
184 if (!replyReadAll.isEmpty()) {
187 if (!replyReadAll.isEmpty()) {
185 tempFile->write(replyReadAll);
188 tempFile->write(replyReadAll);
186 }
189 }
187 tempFile->close();
190 tempFile->close();
188
191
189 // Parse results file
192 // Parse results file
190 if (auto dataSeries
193 if (auto dataSeries
191 = AmdaResultParser::readTxt(tempFile->fileName(), productValueType)) {
194 = AmdaResultParser::readTxt(tempFile->fileName(), productValueType)) {
192 emit dataProvided(dataId, dataSeries, dateTime);
195 emit dataProvided(dataId, dataSeries, dateTime);
193 }
196 }
194 else {
197 else {
195 /// @todo ALX : debug
198 /// @todo ALX : debug
196 emit dataProvidedFailed(dataId);
199 emit dataProvidedFailed(dataId);
197 }
200 }
198 }
201 }
199 m_AcqIdToRequestProgressMap.erase(dataId);
202 m_AcqIdToRequestProgressMap.erase(dataId);
200 }
203 }
201 else {
204 else {
202 qCCritical(LOG_AmdaProvider()) << tr("httpDownloadFinished ERROR");
205 qCCritical(LOG_AmdaProvider()) << tr("httpDownloadFinished ERROR");
203 emit dataProvidedFailed(dataId);
206 emit dataProvidedFailed(dataId);
204 }
207 }
205
208
206 };
209 };
207 auto httpFinishedLambda
210 auto httpFinishedLambda
208 = [this, httpDownloadFinished, tempFile](QNetworkReply *reply, QUuid dataId) noexcept {
211 = [this, httpDownloadFinished, tempFile](QNetworkReply *reply, QUuid dataId) noexcept {
209
212
210 // Don't do anything if the reply was abort
213 // Don't do anything if the reply was abort
211 if (reply->error() == QNetworkReply::NoError) {
214 if (reply->error() == QNetworkReply::NoError) {
212 auto downloadFileUrl = QUrl{QString{reply->readAll()}.trimmed()};
215 auto downloadFileUrl = QUrl{QString{reply->readAll()}.trimmed()};
213
216
214 qCInfo(LOG_AmdaProvider())
217 qCDebug(LOG_AmdaProvider()) << tr("AmdaProvider::retrieveData downloadFileUrl:")
215 << tr("TORM AmdaProvider::retrieveData downloadFileUrl:") << downloadFileUrl;
218 << downloadFileUrl;
216 // Executes request for downloading file //
219 // Executes request for downloading file //
217
220
218 // Creates destination file
221 // Creates destination file
219 if (tempFile->open()) {
222 if (tempFile->open()) {
220 // Executes request and store the request for progression
223 // Executes request and store the request for progression
221 auto request = std::make_shared<QNetworkRequest>(downloadFileUrl);
224 auto request = std::make_shared<QNetworkRequest>(downloadFileUrl);
222 updateRequestProgress(dataId, request, 0.0);
225 updateRequestProgress(dataId, request, 0.0);
223 emit requestConstructed(request, dataId, httpDownloadFinished);
226 emit requestConstructed(request, dataId, httpDownloadFinished);
224 }
227 }
225 else {
228 else {
226 emit dataProvidedFailed(dataId);
229 emit dataProvidedFailed(dataId);
227 }
230 }
228 }
231 }
229 else {
232 else {
230 qCCritical(LOG_AmdaProvider()) << tr("httpFinishedLambda ERROR");
233 qCCritical(LOG_AmdaProvider()) << tr("httpFinishedLambda ERROR");
231 m_AcqIdToRequestProgressMap.erase(dataId);
234 m_AcqIdToRequestProgressMap.erase(dataId);
232 emit dataProvidedFailed(dataId);
235 emit dataProvidedFailed(dataId);
233 }
236 }
234 };
237 };
235
238
236 // //////////////// //
239 // //////////////// //
237 // Executes request //
240 // Executes request //
238 // //////////////// //
241 // //////////////// //
239
242
240 auto request = std::make_shared<QNetworkRequest>(url);
243 auto request = std::make_shared<QNetworkRequest>(url);
241 qCDebug(LOG_AmdaProvider()) << tr("First Request creation") << request.get();
242 updateRequestProgress(token, request, 0.0);
244 updateRequestProgress(token, request, 0.0);
243
245
244 emit requestConstructed(request, token, httpFinishedLambda);
246 emit requestConstructed(request, token, httpFinishedLambda);
245 }
247 }
246
248
247 void AmdaProvider::updateRequestProgress(QUuid acqIdentifier,
249 void AmdaProvider::updateRequestProgress(QUuid acqIdentifier,
248 std::shared_ptr<QNetworkRequest> request, double progress)
250 std::shared_ptr<QNetworkRequest> request, double progress)
249 {
251 {
250 qCDebug(LOG_AmdaProvider()) << tr("updateRequestProgress request") << request.get();
251 auto acqIdToRequestProgressMapIt = m_AcqIdToRequestProgressMap.find(acqIdentifier);
252 auto acqIdToRequestProgressMapIt = m_AcqIdToRequestProgressMap.find(acqIdentifier);
252 if (acqIdToRequestProgressMapIt != m_AcqIdToRequestProgressMap.end()) {
253 if (acqIdToRequestProgressMapIt != m_AcqIdToRequestProgressMap.end()) {
253 auto &requestProgressMap = acqIdToRequestProgressMapIt->second;
254 auto &requestProgressMap = acqIdToRequestProgressMapIt->second;
254 auto requestProgressMapIt = requestProgressMap.find(request);
255 auto requestProgressMapIt = requestProgressMap.find(request);
255 if (requestProgressMapIt != requestProgressMap.end()) {
256 if (requestProgressMapIt != requestProgressMap.end()) {
256 requestProgressMapIt->second = progress;
257 requestProgressMapIt->second = progress;
257 qCDebug(LOG_AmdaProvider()) << tr("updateRequestProgress new progress for request")
258 qCDebug(LOG_AmdaProvider()) << tr("updateRequestProgress new progress for request")
258 << acqIdentifier << request.get() << progress;
259 << acqIdentifier << request.get() << progress;
259 }
260 }
260 else {
261 else {
261 qCDebug(LOG_AmdaProvider()) << tr("updateRequestProgress new request") << acqIdentifier
262 qCDebug(LOG_AmdaProvider()) << tr("updateRequestProgress new request") << acqIdentifier
262 << request.get() << progress;
263 << request.get() << progress;
263 acqIdToRequestProgressMapIt->second.insert(std::make_pair(request, progress));
264 acqIdToRequestProgressMapIt->second.insert(std::make_pair(request, progress));
264 }
265 }
265 }
266 }
266 else {
267 else {
267 qCDebug(LOG_AmdaProvider()) << tr("updateRequestProgress new acqIdentifier")
268 qCDebug(LOG_AmdaProvider()) << tr("updateRequestProgress new acqIdentifier")
268 << acqIdentifier << request.get() << progress;
269 << acqIdentifier << request.get() << progress;
269 auto requestProgressMap = std::map<std::shared_ptr<QNetworkRequest>, double>{};
270 auto requestProgressMap = std::map<std::shared_ptr<QNetworkRequest>, double>{};
270 requestProgressMap.insert(std::make_pair(request, progress));
271 requestProgressMap.insert(std::make_pair(request, progress));
271 m_AcqIdToRequestProgressMap.insert(
272 m_AcqIdToRequestProgressMap.insert(
272 std::make_pair(acqIdentifier, std::move(requestProgressMap)));
273 std::make_pair(acqIdentifier, std::move(requestProgressMap)));
273 }
274 }
274 }
275 }
@@ -1,268 +1,268
1 #include "FuzzingOperations.h"
1 #include "FuzzingOperations.h"
2 #include "FuzzingUtils.h"
2 #include "FuzzingUtils.h"
3
3
4 #include <Data/IDataProvider.h>
4 #include <Data/IDataProvider.h>
5
5
6 #include <Variable/Variable.h>
6 #include <Variable/Variable.h>
7 #include <Variable/VariableController.h>
7 #include <Variable/VariableController.h>
8
8
9 #include <QUuid>
9 #include <QUuid>
10
10
11 #include <functional>
11 #include <functional>
12
12
13 Q_LOGGING_CATEGORY(LOG_FuzzingOperations, "FuzzingOperations")
13 Q_LOGGING_CATEGORY(LOG_FuzzingOperations, "FuzzingOperations")
14
14
15 namespace {
15 namespace {
16
16
17 struct CreateOperation : public IFuzzingOperation {
17 struct CreateOperation : public IFuzzingOperation {
18 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
18 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
19 {
19 {
20 // A variable can be created only if it doesn't exist yet
20 // A variable can be created only if it doesn't exist yet
21 return fuzzingState.variableState(variableId).m_Variable == nullptr;
21 return fuzzingState.variableState(variableId).m_Variable == nullptr;
22 }
22 }
23
23
24 void execute(VariableId variableId, FuzzingState &fuzzingState,
24 void execute(VariableId variableId, FuzzingState &fuzzingState,
25 VariableController &variableController,
25 VariableController &variableController,
26 const Properties &properties) const override
26 const Properties &properties) const override
27 {
27 {
28 // Retrieves metadata pool from properties, and choose one of the metadata entries to
28 // Retrieves metadata pool from properties, and choose one of the metadata entries to
29 // associate it with the variable
29 // associate it with the variable
30 auto metaDataPool = properties.value(METADATA_POOL_PROPERTY).value<MetadataPool>();
30 auto metaDataPool = properties.value(METADATA_POOL_PROPERTY).value<MetadataPool>();
31 auto variableMetadata = RandomGenerator::instance().randomChoice(metaDataPool);
31 auto variableMetadata = RandomGenerator::instance().randomChoice(metaDataPool);
32
32
33 // Retrieves provider
33 // Retrieves provider
34 auto variableProvider
34 auto variableProvider
35 = properties.value(PROVIDER_PROPERTY).value<std::shared_ptr<IDataProvider> >();
35 = properties.value(PROVIDER_PROPERTY).value<std::shared_ptr<IDataProvider> >();
36
36
37 auto variableName = QString{"Var_%1"}.arg(QUuid::createUuid().toString());
37 auto variableName = QString{"Var_%1"}.arg(QUuid::createUuid().toString());
38 qCInfo(LOG_FuzzingOperations()).noquote() << "Creating variable" << variableName
38 qCInfo(LOG_FuzzingOperations()).noquote() << "Creating variable" << variableName
39 << "(metadata:" << variableMetadata << ")...";
39 << "(metadata:" << variableMetadata << ")...";
40
40
41 auto newVariable
41 auto newVariable
42 = variableController.createVariable(variableName, variableMetadata, variableProvider);
42 = variableController.createVariable(variableName, variableMetadata, variableProvider);
43
43
44 // Updates variable's state
44 // Updates variable's state
45 auto &variableState = fuzzingState.variableState(variableId);
45 auto &variableState = fuzzingState.variableState(variableId);
46 variableState.m_Range = properties.value(INITIAL_RANGE_PROPERTY).value<SqpRange>();
46 variableState.m_Range = properties.value(INITIAL_RANGE_PROPERTY).value<SqpRange>();
47 std::swap(variableState.m_Variable, newVariable);
47 std::swap(variableState.m_Variable, newVariable);
48 }
48 }
49 };
49 };
50
50
51 struct DeleteOperation : public IFuzzingOperation {
51 struct DeleteOperation : public IFuzzingOperation {
52 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
52 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
53 {
53 {
54 // A variable can be delete only if it exists
54 // A variable can be delete only if it exists
55 return fuzzingState.variableState(variableId).m_Variable != nullptr;
55 return fuzzingState.variableState(variableId).m_Variable != nullptr;
56 }
56 }
57
57
58 void execute(VariableId variableId, FuzzingState &fuzzingState,
58 void execute(VariableId variableId, FuzzingState &fuzzingState,
59 VariableController &variableController, const Properties &) const override
59 VariableController &variableController, const Properties &) const override
60 {
60 {
61 auto &variableState = fuzzingState.variableState(variableId);
61 auto &variableState = fuzzingState.variableState(variableId);
62
62
63 qCInfo(LOG_FuzzingOperations()).noquote() << "Deleting variable"
63 qCInfo(LOG_FuzzingOperations()).noquote() << "Deleting variable"
64 << variableState.m_Variable->name() << "...";
64 << variableState.m_Variable->name() << "...";
65 variableController.deleteVariable(variableState.m_Variable);
65 variableController.deleteVariable(variableState.m_Variable);
66
66
67 // Updates variable's state
67 // Updates variable's state
68 variableState.m_Range = INVALID_RANGE;
68 variableState.m_Range = INVALID_RANGE;
69 variableState.m_Variable = nullptr;
69 variableState.m_Variable = nullptr;
70
70
71 // Desynchronizes the variable if it was in a sync group
71 // Desynchronizes the variable if it was in a sync group
72 auto syncGroupId = fuzzingState.syncGroupId(variableId);
72 auto syncGroupId = fuzzingState.syncGroupId(variableId);
73 fuzzingState.desynchronizeVariable(variableId, syncGroupId);
73 fuzzingState.desynchronizeVariable(variableId, syncGroupId);
74 }
74 }
75 };
75 };
76
76
77 /**
77 /**
78 * Defines a move operation through a range.
78 * Defines a move operation through a range.
79 *
79 *
80 * A move operation is determined by three functions:
80 * A move operation is determined by three functions:
81 * - Two 'move' functions, used to indicate in which direction the beginning and the end of a range
81 * - Two 'move' functions, used to indicate in which direction the beginning and the end of a range
82 * are going during the operation. These functions will be:
82 * are going during the operation. These functions will be:
83 * -- {<- / <-} for pan left
83 * -- {<- / <-} for pan left
84 * -- {-> / ->} for pan right
84 * -- {-> / ->} for pan right
85 * -- {-> / <-} for zoom in
85 * -- {-> / <-} for zoom in
86 * -- {<- / ->} for zoom out
86 * -- {<- / ->} for zoom out
87 * - One 'max move' functions, used to compute the max delta at which the operation can move a
87 * - One 'max move' functions, used to compute the max delta at which the operation can move a
88 * range, according to a max range. For exemple, for a range of {1, 5} and a max range of {0, 10},
88 * range, according to a max range. For exemple, for a range of {1, 5} and a max range of {0, 10},
89 * max deltas will be:
89 * max deltas will be:
90 * -- {0, 4} for pan left
90 * -- {0, 4} for pan left
91 * -- {6, 10} for pan right
91 * -- {6, 10} for pan right
92 * -- {3, 3} for zoom in
92 * -- {3, 3} for zoom in
93 * -- {0, 6} for zoom out (same spacing left and right)
93 * -- {0, 6} for zoom out (same spacing left and right)
94 */
94 */
95 struct MoveOperation : public IFuzzingOperation {
95 struct MoveOperation : public IFuzzingOperation {
96 using MoveFunction = std::function<double(double currentValue, double maxValue)>;
96 using MoveFunction = std::function<double(double currentValue, double maxValue)>;
97 using MaxMoveFunction = std::function<double(const SqpRange &range, const SqpRange &maxRange)>;
97 using MaxMoveFunction = std::function<double(const SqpRange &range, const SqpRange &maxRange)>;
98
98
99 explicit MoveOperation(MoveFunction rangeStartMoveFun, MoveFunction rangeEndMoveFun,
99 explicit MoveOperation(MoveFunction rangeStartMoveFun, MoveFunction rangeEndMoveFun,
100 MaxMoveFunction maxMoveFun,
100 MaxMoveFunction maxMoveFun,
101 const QString &label = QStringLiteral("Move operation"))
101 const QString &label = QStringLiteral("Move operation"))
102 : m_RangeStartMoveFun{std::move(rangeStartMoveFun)},
102 : m_RangeStartMoveFun{std::move(rangeStartMoveFun)},
103 m_RangeEndMoveFun{std::move(rangeEndMoveFun)},
103 m_RangeEndMoveFun{std::move(rangeEndMoveFun)},
104 m_MaxMoveFun{std::move(maxMoveFun)},
104 m_MaxMoveFun{std::move(maxMoveFun)},
105 m_Label{label}
105 m_Label{label}
106 {
106 {
107 }
107 }
108
108
109 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
109 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
110 {
110 {
111 return fuzzingState.variableState(variableId).m_Variable != nullptr;
111 return fuzzingState.variableState(variableId).m_Variable != nullptr;
112 }
112 }
113
113
114 void execute(VariableId variableId, FuzzingState &fuzzingState,
114 void execute(VariableId variableId, FuzzingState &fuzzingState,
115 VariableController &variableController,
115 VariableController &variableController,
116 const Properties &properties) const override
116 const Properties &properties) const override
117 {
117 {
118 auto &variableState = fuzzingState.variableState(variableId);
118 auto &variableState = fuzzingState.variableState(variableId);
119 auto variable = variableState.m_Variable;
119 auto variable = variableState.m_Variable;
120
120
121 // Gets the max range defined
121 // Gets the max range defined
122 auto maxRange = properties.value(MAX_RANGE_PROPERTY, QVariant::fromValue(INVALID_RANGE))
122 auto maxRange = properties.value(MAX_RANGE_PROPERTY, QVariant::fromValue(INVALID_RANGE))
123 .value<SqpRange>();
123 .value<SqpRange>();
124 auto variableRange = variableState.m_Range;
124 auto variableRange = variableState.m_Range;
125
125
126 if (maxRange == INVALID_RANGE || variableRange.m_TStart < maxRange.m_TStart
126 if (maxRange == INVALID_RANGE || variableRange.m_TStart < maxRange.m_TStart
127 || variableRange.m_TEnd > maxRange.m_TEnd) {
127 || variableRange.m_TEnd > maxRange.m_TEnd) {
128 qCWarning(LOG_FuzzingOperations()) << "Can't execute operation: invalid max range";
128 qCWarning(LOG_FuzzingOperations()) << "Can't execute operation: invalid max range";
129 return;
129 return;
130 }
130 }
131
131
132 // Computes the max delta at which the variable can move, up to the limits of the max range
132 // Computes the max delta at which the variable can move, up to the limits of the max range
133 auto deltaMax = m_MaxMoveFun(variableRange, maxRange);
133 auto deltaMax = m_MaxMoveFun(variableRange, maxRange);
134
134
135 // Generates random delta that will be used to move variable
135 // Generates random delta that will be used to move variable
136 auto delta = RandomGenerator::instance().generateDouble(0, deltaMax);
136 auto delta = RandomGenerator::instance().generateDouble(0, deltaMax);
137
137
138 // Moves variable to its new range
138 // Moves variable to its new range
139 auto isSynchronized = !fuzzingState.syncGroupId(variableId).isNull();
139 auto isSynchronized = !fuzzingState.syncGroupId(variableId).isNull();
140 auto newVariableRange = SqpRange{m_RangeStartMoveFun(variableRange.m_TStart, delta),
140 auto newVariableRange = SqpRange{m_RangeStartMoveFun(variableRange.m_TStart, delta),
141 m_RangeEndMoveFun(variableRange.m_TEnd, delta)};
141 m_RangeEndMoveFun(variableRange.m_TEnd, delta)};
142 qCInfo(LOG_FuzzingOperations()).noquote() << "Performing" << m_Label << "on"
142 qCInfo(LOG_FuzzingOperations()).noquote() << "Performing" << m_Label << "on"
143 << variable->name() << "(from" << variableRange
143 << variable->name() << "(from" << variableRange
144 << "to" << newVariableRange << ")...";
144 << "to" << newVariableRange << ")...";
145 variableController.onRequestDataLoading({variable}, newVariableRange, isSynchronized);
145 variableController.onRequestDataLoading({variable}, newVariableRange, isSynchronized);
146
146
147 // Updates state
147 // Updates state
148 fuzzingState.updateRanges(variableId, newVariableRange);
148 fuzzingState.updateRanges(variableId, newVariableRange);
149 }
149 }
150
150
151 MoveFunction m_RangeStartMoveFun;
151 MoveFunction m_RangeStartMoveFun;
152 MoveFunction m_RangeEndMoveFun;
152 MoveFunction m_RangeEndMoveFun;
153 MaxMoveFunction m_MaxMoveFun;
153 MaxMoveFunction m_MaxMoveFun;
154 QString m_Label;
154 QString m_Label;
155 };
155 };
156
156
157 struct SynchronizeOperation : public IFuzzingOperation {
157 struct SynchronizeOperation : public IFuzzingOperation {
158 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
158 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
159 {
159 {
160 auto variable = fuzzingState.variableState(variableId).m_Variable;
160 auto variable = fuzzingState.variableState(variableId).m_Variable;
161 return variable != nullptr && !fuzzingState.m_SyncGroupsPool.empty()
161 return variable != nullptr && !fuzzingState.m_SyncGroupsPool.empty()
162 && fuzzingState.syncGroupId(variableId).isNull();
162 && fuzzingState.syncGroupId(variableId).isNull();
163 }
163 }
164
164
165 void execute(VariableId variableId, FuzzingState &fuzzingState,
165 void execute(VariableId variableId, FuzzingState &fuzzingState,
166 VariableController &variableController, const Properties &) const override
166 VariableController &variableController, const Properties &) const override
167 {
167 {
168 auto &variableState = fuzzingState.variableState(variableId);
168 auto &variableState = fuzzingState.variableState(variableId);
169
169
170 // Chooses a random synchronization group and adds the variable into sync group
170 // Chooses a random synchronization group and adds the variable into sync group
171 auto syncGroupId = RandomGenerator::instance().randomChoice(fuzzingState.syncGroupsIds());
171 auto syncGroupId = RandomGenerator::instance().randomChoice(fuzzingState.syncGroupsIds());
172 qCInfo(LOG_FuzzingOperations()).noquote() << "Adding" << variableState.m_Variable->name()
172 qCInfo(LOG_FuzzingOperations()).noquote() << "Adding" << variableState.m_Variable->name()
173 << "into synchronization group" << syncGroupId
173 << "into synchronization group" << syncGroupId
174 << "...";
174 << "...";
175 variableController.onAddSynchronized(variableState.m_Variable, syncGroupId);
175 variableController.onAddSynchronized(variableState.m_Variable, syncGroupId);
176
176
177 // Updates state
177 // Updates state
178 fuzzingState.synchronizeVariable(variableId, syncGroupId);
178 fuzzingState.synchronizeVariable(variableId, syncGroupId);
179
179
180 variableController.onRequestDataLoading({variableState.m_Variable}, variableState.m_Range,
180 variableController.onRequestDataLoading({variableState.m_Variable}, variableState.m_Range,
181 false);
181 true);
182 }
182 }
183 };
183 };
184
184
185 struct DesynchronizeOperation : public IFuzzingOperation {
185 struct DesynchronizeOperation : public IFuzzingOperation {
186 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
186 bool canExecute(VariableId variableId, const FuzzingState &fuzzingState) const override
187 {
187 {
188 auto variable = fuzzingState.variableState(variableId).m_Variable;
188 auto variable = fuzzingState.variableState(variableId).m_Variable;
189 return variable != nullptr && !fuzzingState.syncGroupId(variableId).isNull();
189 return variable != nullptr && !fuzzingState.syncGroupId(variableId).isNull();
190 }
190 }
191
191
192 void execute(VariableId variableId, FuzzingState &fuzzingState,
192 void execute(VariableId variableId, FuzzingState &fuzzingState,
193 VariableController &variableController, const Properties &) const override
193 VariableController &variableController, const Properties &) const override
194 {
194 {
195 auto &variableState = fuzzingState.variableState(variableId);
195 auto &variableState = fuzzingState.variableState(variableId);
196
196
197 // Gets the sync group of the variable
197 // Gets the sync group of the variable
198 auto syncGroupId = fuzzingState.syncGroupId(variableId);
198 auto syncGroupId = fuzzingState.syncGroupId(variableId);
199
199
200 qCInfo(LOG_FuzzingOperations()).noquote() << "Removing" << variableState.m_Variable->name()
200 qCInfo(LOG_FuzzingOperations()).noquote() << "Removing" << variableState.m_Variable->name()
201 << "from synchronization group" << syncGroupId
201 << "from synchronization group" << syncGroupId
202 << "...";
202 << "...";
203 variableController.desynchronize(variableState.m_Variable, syncGroupId);
203 variableController.desynchronize(variableState.m_Variable, syncGroupId);
204
204
205 // Updates state
205 // Updates state
206 fuzzingState.desynchronizeVariable(variableId, syncGroupId);
206 fuzzingState.desynchronizeVariable(variableId, syncGroupId);
207 }
207 }
208 };
208 };
209
209
210 struct UnknownOperation : public IFuzzingOperation {
210 struct UnknownOperation : public IFuzzingOperation {
211 bool canExecute(VariableId, const FuzzingState &) const override { return false; }
211 bool canExecute(VariableId, const FuzzingState &) const override { return false; }
212
212
213 void execute(VariableId, FuzzingState &, VariableController &,
213 void execute(VariableId, FuzzingState &, VariableController &,
214 const Properties &) const override
214 const Properties &) const override
215 {
215 {
216 }
216 }
217 };
217 };
218
218
219 } // namespace
219 } // namespace
220
220
221 std::unique_ptr<IFuzzingOperation> FuzzingOperationFactory::create(FuzzingOperationType type)
221 std::unique_ptr<IFuzzingOperation> FuzzingOperationFactory::create(FuzzingOperationType type)
222 {
222 {
223 switch (type) {
223 switch (type) {
224 case FuzzingOperationType::CREATE:
224 case FuzzingOperationType::CREATE:
225 return std::make_unique<CreateOperation>();
225 return std::make_unique<CreateOperation>();
226 case FuzzingOperationType::DELETE:
226 case FuzzingOperationType::DELETE:
227 return std::make_unique<DeleteOperation>();
227 return std::make_unique<DeleteOperation>();
228 case FuzzingOperationType::PAN_LEFT:
228 case FuzzingOperationType::PAN_LEFT:
229 return std::make_unique<MoveOperation>(
229 return std::make_unique<MoveOperation>(
230 std::minus<double>(), std::minus<double>(),
230 std::minus<double>(), std::minus<double>(),
231 [](const SqpRange &range, const SqpRange &maxRange) {
231 [](const SqpRange &range, const SqpRange &maxRange) {
232 return range.m_TStart - maxRange.m_TStart;
232 return range.m_TStart - maxRange.m_TStart;
233 },
233 },
234 QStringLiteral("Pan left operation"));
234 QStringLiteral("Pan left operation"));
235 case FuzzingOperationType::PAN_RIGHT:
235 case FuzzingOperationType::PAN_RIGHT:
236 return std::make_unique<MoveOperation>(
236 return std::make_unique<MoveOperation>(
237 std::plus<double>(), std::plus<double>(),
237 std::plus<double>(), std::plus<double>(),
238 [](const SqpRange &range, const SqpRange &maxRange) {
238 [](const SqpRange &range, const SqpRange &maxRange) {
239 return maxRange.m_TEnd - range.m_TEnd;
239 return maxRange.m_TEnd - range.m_TEnd;
240 },
240 },
241 QStringLiteral("Pan right operation"));
241 QStringLiteral("Pan right operation"));
242 case FuzzingOperationType::ZOOM_IN:
242 case FuzzingOperationType::ZOOM_IN:
243 return std::make_unique<MoveOperation>(
243 return std::make_unique<MoveOperation>(
244 std::plus<double>(), std::minus<double>(),
244 std::plus<double>(), std::minus<double>(),
245 [](const SqpRange &range, const SqpRange &maxRange) {
245 [](const SqpRange &range, const SqpRange &maxRange) {
246 Q_UNUSED(maxRange)
246 Q_UNUSED(maxRange)
247 return range.m_TEnd - (range.m_TStart + range.m_TEnd) / 2.;
247 return range.m_TEnd - (range.m_TStart + range.m_TEnd) / 2.;
248 },
248 },
249 QStringLiteral("Zoom in operation"));
249 QStringLiteral("Zoom in operation"));
250 case FuzzingOperationType::ZOOM_OUT:
250 case FuzzingOperationType::ZOOM_OUT:
251 return std::make_unique<MoveOperation>(
251 return std::make_unique<MoveOperation>(
252 std::minus<double>(), std::plus<double>(),
252 std::minus<double>(), std::plus<double>(),
253 [](const SqpRange &range, const SqpRange &maxRange) {
253 [](const SqpRange &range, const SqpRange &maxRange) {
254 return std::min(range.m_TStart - maxRange.m_TStart,
254 return std::min(range.m_TStart - maxRange.m_TStart,
255 maxRange.m_TEnd - range.m_TEnd);
255 maxRange.m_TEnd - range.m_TEnd);
256 },
256 },
257 QStringLiteral("Zoom out operation"));
257 QStringLiteral("Zoom out operation"));
258 case FuzzingOperationType::SYNCHRONIZE:
258 case FuzzingOperationType::SYNCHRONIZE:
259 return std::make_unique<SynchronizeOperation>();
259 return std::make_unique<SynchronizeOperation>();
260 case FuzzingOperationType::DESYNCHRONIZE:
260 case FuzzingOperationType::DESYNCHRONIZE:
261 return std::make_unique<DesynchronizeOperation>();
261 return std::make_unique<DesynchronizeOperation>();
262 default:
262 default:
263 // Default case returns unknown operation
263 // Default case returns unknown operation
264 break;
264 break;
265 }
265 }
266
266
267 return std::make_unique<UnknownOperation>();
267 return std::make_unique<UnknownOperation>();
268 }
268 }
@@ -1,558 +1,560
1 #include "FuzzingDefs.h"
1 #include "FuzzingDefs.h"
2 #include "FuzzingOperations.h"
2 #include "FuzzingOperations.h"
3 #include "FuzzingUtils.h"
3 #include "FuzzingUtils.h"
4 #include "FuzzingValidators.h"
4 #include "FuzzingValidators.h"
5
5
6 #include "AmdaProvider.h"
6 #include "AmdaProvider.h"
7
7
8 #include <Common/SignalWaiter.h>
8 #include <Common/SignalWaiter.h>
9 #include <Network/NetworkController.h>
9 #include <Network/NetworkController.h>
10 #include <Settings/SqpSettingsDefs.h>
10 #include <Settings/SqpSettingsDefs.h>
11 #include <SqpApplication.h>
11 #include <SqpApplication.h>
12 #include <Time/TimeController.h>
12 #include <Time/TimeController.h>
13 #include <Variable/Variable.h>
13 #include <Variable/Variable.h>
14 #include <Variable/VariableController.h>
14 #include <Variable/VariableController.h>
15
15
16 #include <QLoggingCategory>
16 #include <QLoggingCategory>
17 #include <QObject>
17 #include <QObject>
18 #include <QtTest>
18 #include <QtTest>
19
19
20 #include <memory>
20 #include <memory>
21
21
22 Q_LOGGING_CATEGORY(LOG_TestAmdaFuzzing, "TestAmdaFuzzing")
22 Q_LOGGING_CATEGORY(LOG_TestAmdaFuzzing, "TestAmdaFuzzing")
23
23
24 /**
24 /**
25 * Macro used to generate a getter for a property in @sa FuzzingTest. The macro generates a static
25 * Macro used to generate a getter for a property in @sa FuzzingTest. The macro generates a static
26 * attribute that is initialized by searching in properties the property and use a default value if
26 * attribute that is initialized by searching in properties the property and use a default value if
27 * it's not present. Macro arguments are:
27 * it's not present. Macro arguments are:
28 * - GETTER_NAME : name of the getter
28 * - GETTER_NAME : name of the getter
29 * - PROPERTY_NAME: used to generate constants for property's name ({PROPERTY_NAME}_PROPERTY) and
29 * - PROPERTY_NAME: used to generate constants for property's name ({PROPERTY_NAME}_PROPERTY) and
30 * default value ({PROPERTY_NAME}_DEFAULT_VALUE)
30 * default value ({PROPERTY_NAME}_DEFAULT_VALUE)
31 * - TYPE : return type of the getter
31 * - TYPE : return type of the getter
32 */
32 */
33 // clang-format off
33 // clang-format off
34 #define DECLARE_PROPERTY_GETTER(GETTER_NAME, PROPERTY_NAME, TYPE) \
34 #define DECLARE_PROPERTY_GETTER(GETTER_NAME, PROPERTY_NAME, TYPE) \
35 TYPE GETTER_NAME() const \
35 TYPE GETTER_NAME() const \
36 { \
36 { \
37 static auto result = m_Properties.value(PROPERTY_NAME##_PROPERTY, PROPERTY_NAME##_DEFAULT_VALUE).value<TYPE>(); \
37 static auto result = m_Properties.value(PROPERTY_NAME##_PROPERTY, PROPERTY_NAME##_DEFAULT_VALUE).value<TYPE>(); \
38 return result; \
38 return result; \
39 } \
39 } \
40 // clang-format on
40 // clang-format on
41
41
42 namespace {
42 namespace {
43
43
44 // /////// //
44 // /////// //
45 // Aliases //
45 // Aliases //
46 // /////// //
46 // /////// //
47
47
48 using IntPair = std::pair<int, int>;
48 using IntPair = std::pair<int, int>;
49 using Weight = double;
49 using Weight = double;
50 using Weights = std::vector<Weight>;
50 using Weights = std::vector<Weight>;
51
51
52 struct OperationProperty {
52 struct OperationProperty {
53 Weight m_Weight{1.};
53 Weight m_Weight{1.};
54 bool m_WaitAcquisition{false};
54 bool m_WaitAcquisition{false};
55 };
55 };
56
56
57 using VariableOperation = std::pair<VariableId, std::shared_ptr<IFuzzingOperation> >;
57 using VariableOperation = std::pair<VariableId, std::shared_ptr<IFuzzingOperation> >;
58 using VariablesOperations = std::vector<VariableOperation>;
58 using VariablesOperations = std::vector<VariableOperation>;
59
59
60 struct CustomVariableOperation {
60 struct CustomVariableOperation {
61 VariableOperation m_VariableOperation{};
61 VariableOperation m_VariableOperation{};
62 bool m_WaitAcquisition{false};
62 bool m_WaitAcquisition{false};
63 };
63 };
64 using CustomVariablesOperations = std::vector<CustomVariableOperation>;
64 using CustomVariablesOperations = std::vector<CustomVariableOperation>;
65
65
66 using OperationsTypes = std::map<FuzzingOperationType, OperationProperty>;
66 using OperationsTypes = std::map<FuzzingOperationType, OperationProperty>;
67 using OperationsPool = std::map<std::shared_ptr<IFuzzingOperation>, OperationProperty>;
67 using OperationsPool = std::map<std::shared_ptr<IFuzzingOperation>, OperationProperty>;
68
68
69 using Validators = std::vector<std::shared_ptr<IFuzzingValidator> >;
69 using Validators = std::vector<std::shared_ptr<IFuzzingValidator> >;
70
70
71 // ///////// //
71 // ///////// //
72 // Constants //
72 // Constants //
73 // ///////// //
73 // ///////// //
74
74
75 // Defaults values used when the associated properties have not been set for the test
75 // Defaults values used when the associated properties have not been set for the test
76 const auto ACQUISITION_TIMEOUT_DEFAULT_VALUE = 30000;
76 const auto ACQUISITION_TIMEOUT_DEFAULT_VALUE = 100000;
77 const auto NB_MAX_OPERATIONS_DEFAULT_VALUE = 100;
77 const auto NB_MAX_OPERATIONS_DEFAULT_VALUE = 160;
78 const auto NB_MAX_SYNC_GROUPS_DEFAULT_VALUE = 1;
78 const auto NB_MAX_SYNC_GROUPS_DEFAULT_VALUE = 8;
79 const auto NB_MAX_VARIABLES_DEFAULT_VALUE = 2;
79 const auto NB_MAX_VARIABLES_DEFAULT_VALUE = 30;
80 const auto AVAILABLE_OPERATIONS_DEFAULT_VALUE = QVariant::fromValue(
80 const auto AVAILABLE_OPERATIONS_DEFAULT_VALUE = QVariant::fromValue(
81 OperationsTypes{{FuzzingOperationType::CREATE, {400., true}},
81 OperationsTypes{{FuzzingOperationType::CREATE, {40000., true}},
82 {FuzzingOperationType::DELETE, {0.0}}, // Delete operation is less frequent
82 {FuzzingOperationType::DELETE, {0.0}}, // Delete operation is less frequent
83 {FuzzingOperationType::PAN_LEFT, {1.}},
83 {FuzzingOperationType::PAN_LEFT, {1.}},
84 {FuzzingOperationType::PAN_RIGHT, {1.}},
84 {FuzzingOperationType::PAN_RIGHT, {1.}},
85 {FuzzingOperationType::ZOOM_IN, {0.}},
85 {FuzzingOperationType::ZOOM_IN, {1.}},
86 {FuzzingOperationType::ZOOM_OUT, {0.}},
86 {FuzzingOperationType::ZOOM_OUT, {1.}},
87 {FuzzingOperationType::SYNCHRONIZE, {4000.0}},
87 {FuzzingOperationType::SYNCHRONIZE, {500.0}},
88 {FuzzingOperationType::DESYNCHRONIZE, {0.4}}});
88 {FuzzingOperationType::DESYNCHRONIZE, {0.0}}});
89 const auto CACHE_TOLERANCE_DEFAULT_VALUE = 0.2;
89 const auto CACHE_TOLERANCE_DEFAULT_VALUE = 0.2;
90
90
91 /// Min/max delays between each operation (in ms)
91 /// Min/max delays between each operation (in ms)
92 const auto OPERATION_DELAY_BOUNDS_DEFAULT_VALUE = QVariant::fromValue(std::make_pair(20, 20));
92 const auto OPERATION_DELAY_BOUNDS_DEFAULT_VALUE = QVariant::fromValue(std::make_pair(20, 3000));
93
93
94 /// Validators for the tests (executed in the order in which they're defined)
94 /// Validators for the tests (executed in the order in which they're defined)
95 const auto VALIDATORS_DEFAULT_VALUE = QVariant::fromValue(
95 const auto VALIDATORS_DEFAULT_VALUE = QVariant::fromValue(
96 ValidatorsTypes{{FuzzingValidatorType::RANGE, FuzzingValidatorType::DATA}});
96 ValidatorsTypes{{FuzzingValidatorType::RANGE, FuzzingValidatorType::DATA}});
97
97
98 /// Min/max number of operations to execute before calling validation
98 /// Min/max number of operations to execute before calling validation
99 const auto VALIDATION_FREQUENCY_BOUNDS_DEFAULT_VALUE = QVariant::fromValue(std::make_pair(2, 2));
99 const auto VALIDATION_FREQUENCY_BOUNDS_DEFAULT_VALUE = QVariant::fromValue(std::make_pair(2, 10));
100
100
101
101
102 // /////// //////
102 // /////// //////
103 // CUSTOM CASE //
103 // CUSTOM CASE //
104 // /////// //////
104 // /////// //////
105
105
106 auto op = [](auto type){
106 auto op = [](auto type){
107 return FuzzingOperationFactory::create(type);
107 return FuzzingOperationFactory::create(type);
108 };
108 };
109
109
110
110
111 const QVariant CUSTOM_CASE_ONE =QVariant::fromValue(CustomVariablesOperations{{{0, op(FuzzingOperationType::CREATE)}, true},
111 const QVariant CUSTOM_CASE_ONE =QVariant::fromValue(CustomVariablesOperations{{{0, op(FuzzingOperationType::CREATE)}, true},
112 {{0, op(FuzzingOperationType::SYNCHRONIZE)}},
112 {{0, op(FuzzingOperationType::SYNCHRONIZE)}},
113 {{1, op(FuzzingOperationType::CREATE)}, true},
113 {{1, op(FuzzingOperationType::CREATE)}, true},
114 {{1, op(FuzzingOperationType::SYNCHRONIZE)}},
114 {{1, op(FuzzingOperationType::SYNCHRONIZE)}},
115 {{0, op(FuzzingOperationType::PAN_LEFT)}},
115 {{0, op(FuzzingOperationType::PAN_LEFT)}},
116 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
116 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
117 {{0, op(FuzzingOperationType::PAN_LEFT)}},
117 {{0, op(FuzzingOperationType::PAN_LEFT)}},
118 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
118 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
119 {{0, op(FuzzingOperationType::PAN_LEFT)}},
119 {{0, op(FuzzingOperationType::PAN_LEFT)}},
120 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
120 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
121 {{0, op(FuzzingOperationType::PAN_LEFT)}},
121 {{0, op(FuzzingOperationType::PAN_LEFT)}},
122 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
122 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
123 {{0, op(FuzzingOperationType::PAN_LEFT)}},
123 {{0, op(FuzzingOperationType::PAN_LEFT)}},
124 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
124 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
125 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
125 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
126 {{1, op(FuzzingOperationType::PAN_LEFT)}},
126 {{1, op(FuzzingOperationType::PAN_LEFT)}},
127 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
127 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
128 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
128 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
129 {{0, op(FuzzingOperationType::PAN_LEFT)}},
129 {{0, op(FuzzingOperationType::PAN_LEFT)}},
130 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
130 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
131 {{0, op(FuzzingOperationType::PAN_LEFT)}},
131 {{0, op(FuzzingOperationType::PAN_LEFT)}},
132 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
132 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
133 {{0, op(FuzzingOperationType::PAN_LEFT)}},
133 {{0, op(FuzzingOperationType::PAN_LEFT)}},
134 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
134 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
135 {{0, op(FuzzingOperationType::PAN_LEFT)}},
135 {{0, op(FuzzingOperationType::PAN_LEFT)}},
136 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
136 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
137 {{0, op(FuzzingOperationType::PAN_LEFT)}},
137 {{0, op(FuzzingOperationType::PAN_LEFT)}},
138 {{1, op(FuzzingOperationType::PAN_LEFT)}},
138 {{1, op(FuzzingOperationType::PAN_LEFT)}},
139 {{0, op(FuzzingOperationType::PAN_LEFT)}},
139 {{0, op(FuzzingOperationType::PAN_LEFT)}},
140 {{1, op(FuzzingOperationType::PAN_LEFT)}},
140 {{1, op(FuzzingOperationType::PAN_LEFT)}},
141 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
141 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
142 {{1, op(FuzzingOperationType::PAN_LEFT)}},
142 {{1, op(FuzzingOperationType::PAN_LEFT)}},
143 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
143 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
144 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
144 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
145 {{0, op(FuzzingOperationType::PAN_LEFT)}},
145 {{0, op(FuzzingOperationType::PAN_LEFT)}},
146 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
146 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
147 {{0, op(FuzzingOperationType::PAN_LEFT)}},
147 {{0, op(FuzzingOperationType::PAN_LEFT)}},
148 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
148 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
149 {{0, op(FuzzingOperationType::PAN_LEFT)}},
149 {{0, op(FuzzingOperationType::PAN_LEFT)}},
150 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
150 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
151 {{0, op(FuzzingOperationType::PAN_LEFT)}},
151 {{0, op(FuzzingOperationType::PAN_LEFT)}},
152 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
152 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
153 {{0, op(FuzzingOperationType::PAN_LEFT)}},
153 {{0, op(FuzzingOperationType::PAN_LEFT)}},
154 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
154 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
155 {{0, op(FuzzingOperationType::PAN_LEFT)}},
155 {{0, op(FuzzingOperationType::PAN_LEFT)}},
156 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
156 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
157 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
157 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
158 {{1, op(FuzzingOperationType::PAN_LEFT)}},
158 {{1, op(FuzzingOperationType::PAN_LEFT)}},
159 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
159 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
160 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
160 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
161 {{0, op(FuzzingOperationType::PAN_LEFT)}},
161 {{0, op(FuzzingOperationType::PAN_LEFT)}},
162 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
162 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
163 {{0, op(FuzzingOperationType::PAN_LEFT)}},
163 {{0, op(FuzzingOperationType::PAN_LEFT)}},
164 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
164 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
165 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
165 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
166 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
166 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
167 {{0, op(FuzzingOperationType::PAN_LEFT)}},
167 {{0, op(FuzzingOperationType::PAN_LEFT)}},
168 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
168 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
169 {{0, op(FuzzingOperationType::PAN_LEFT)}},
169 {{0, op(FuzzingOperationType::PAN_LEFT)}},
170 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
170 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
171 {{0, op(FuzzingOperationType::PAN_LEFT)}},
171 {{0, op(FuzzingOperationType::PAN_LEFT)}},
172 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
172 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
173 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
173 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
174 {{1, op(FuzzingOperationType::PAN_LEFT)}},
174 {{1, op(FuzzingOperationType::PAN_LEFT)}},
175 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
175 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
176 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
176 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
177 {{0, op(FuzzingOperationType::PAN_LEFT)}},
177 {{0, op(FuzzingOperationType::PAN_LEFT)}},
178 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
178 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
179 {{0, op(FuzzingOperationType::PAN_LEFT)}},
179 {{0, op(FuzzingOperationType::PAN_LEFT)}},
180 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
180 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
181 {{0, op(FuzzingOperationType::PAN_LEFT)}},
181 {{0, op(FuzzingOperationType::PAN_LEFT)}},
182 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
182 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
183 {{0, op(FuzzingOperationType::PAN_LEFT)}},
183 {{0, op(FuzzingOperationType::PAN_LEFT)}},
184 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
184 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
185 {{0, op(FuzzingOperationType::PAN_LEFT)}},
185 {{0, op(FuzzingOperationType::PAN_LEFT)}},
186 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
186 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
187 {{0, op(FuzzingOperationType::PAN_LEFT)}},
187 {{0, op(FuzzingOperationType::PAN_LEFT)}},
188 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
188 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
189 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
189 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
190 {{1, op(FuzzingOperationType::PAN_LEFT)}},
190 {{1, op(FuzzingOperationType::PAN_LEFT)}},
191 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
191 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
192 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
192 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
193 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
193 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
194 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
194 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
195 {{0, op(FuzzingOperationType::PAN_LEFT)}},
195 {{0, op(FuzzingOperationType::PAN_LEFT)}},
196 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
196 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
197 {{0, op(FuzzingOperationType::PAN_LEFT)}},
197 {{0, op(FuzzingOperationType::PAN_LEFT)}},
198 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
198 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
199 {{0, op(FuzzingOperationType::PAN_LEFT)}},
199 {{0, op(FuzzingOperationType::PAN_LEFT)}},
200 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
200 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
201 {{0, op(FuzzingOperationType::PAN_LEFT)}},
201 {{0, op(FuzzingOperationType::PAN_LEFT)}},
202 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
202 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
203 {{0, op(FuzzingOperationType::PAN_LEFT)}},
203 {{0, op(FuzzingOperationType::PAN_LEFT)}},
204 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
204 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
205 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
205 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
206 {{1, op(FuzzingOperationType::PAN_LEFT)}},
206 {{1, op(FuzzingOperationType::PAN_LEFT)}},
207 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
207 {{0, op(FuzzingOperationType::PAN_RIGHT)}},
208 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
208 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
209 {{0, op(FuzzingOperationType::PAN_LEFT)}},
209 {{0, op(FuzzingOperationType::PAN_LEFT)}},
210 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
210 {{1, op(FuzzingOperationType::PAN_RIGHT)}},
211 });
211 });
212
212
213 const QVariant CUSTOM_CASE_TWO =QVariant::fromValue(CustomVariablesOperations{{{0, op(FuzzingOperationType::CREATE)}, true},
213 const QVariant CUSTOM_CASE_TWO =QVariant::fromValue(CustomVariablesOperations{{{0, op(FuzzingOperationType::CREATE)}, true},
214 {{0, op(FuzzingOperationType::SYNCHRONIZE)}},
214 {{0, op(FuzzingOperationType::SYNCHRONIZE)}},
215 {{1, op(FuzzingOperationType::CREATE)}, true},
215 {{1, op(FuzzingOperationType::CREATE)}, true},
216 {{1, op(FuzzingOperationType::SYNCHRONIZE)}},
216 {{1, op(FuzzingOperationType::SYNCHRONIZE)}},
217 {{1, op(FuzzingOperationType::ZOOM_OUT)}},
217 {{1, op(FuzzingOperationType::ZOOM_OUT)}},
218 {{1, op(FuzzingOperationType::ZOOM_IN)}},
218 {{1, op(FuzzingOperationType::ZOOM_IN)}},
219 });
219 });
220
220
221 // /////// //
221 // /////// //
222 // Methods //
222 // Methods //
223 // /////// //
223 // /////// //
224
224
225 /// Goes through the variables pool and operations pool to determine the set of {variable/operation}
225 /// Goes through the variables pool and operations pool to determine the set of {variable/operation}
226 /// pairs that are valid (i.e. operation that can be executed on variable)
226 /// pairs that are valid (i.e. operation that can be executed on variable)
227 std::pair<VariablesOperations, Weights> availableOperations(const FuzzingState &fuzzingState,
227 std::pair<VariablesOperations, Weights> availableOperations(const FuzzingState &fuzzingState,
228 const OperationsPool &operationsPool)
228 const OperationsPool &operationsPool)
229 {
229 {
230 VariablesOperations result{};
230 VariablesOperations result{};
231 Weights weights{};
231 Weights weights{};
232
232
233 for (const auto &variablesPoolEntry : fuzzingState.m_VariablesPool) {
233 for (const auto &variablesPoolEntry : fuzzingState.m_VariablesPool) {
234 auto variableId = variablesPoolEntry.first;
234 auto variableId = variablesPoolEntry.first;
235
235
236 for (const auto &operationsPoolEntry : operationsPool) {
236 for (const auto &operationsPoolEntry : operationsPool) {
237 auto operation = operationsPoolEntry.first;
237 auto operation = operationsPoolEntry.first;
238 auto operationProperty = operationsPoolEntry.second;
238 auto operationProperty = operationsPoolEntry.second;
239
239
240 // A pair is valid if the current operation can be executed on the current variable
240 // A pair is valid if the current operation can be executed on the current variable
241 if (operation->canExecute(variableId, fuzzingState)) {
241 if (operation->canExecute(variableId, fuzzingState)) {
242 result.push_back({variableId, operation});
242 result.push_back({variableId, operation});
243 weights.push_back(operationProperty.m_Weight);
243 weights.push_back(operationProperty.m_Weight);
244 }
244 }
245 }
245 }
246 }
246 }
247
247
248 return {result, weights};
248 return {result, weights};
249 }
249 }
250
250
251 OperationsPool createOperationsPool(const OperationsTypes &types)
251 OperationsPool createOperationsPool(const OperationsTypes &types)
252 {
252 {
253 OperationsPool result{};
253 OperationsPool result{};
254
254
255 std::transform(
255 std::transform(
256 types.cbegin(), types.cend(), std::inserter(result, result.end()), [](const auto &type) {
256 types.cbegin(), types.cend(), std::inserter(result, result.end()), [](const auto &type) {
257 return std::make_pair(FuzzingOperationFactory::create(type.first), type.second);
257 return std::make_pair(FuzzingOperationFactory::create(type.first), type.second);
258 });
258 });
259
259
260 return result;
260 return result;
261 }
261 }
262
262
263 Validators createValidators(const ValidatorsTypes &types)
263 Validators createValidators(const ValidatorsTypes &types)
264 {
264 {
265 Validators result{};
265 Validators result{};
266
266
267 std::transform(types.cbegin(), types.cend(), std::inserter(result, result.end()),
267 std::transform(types.cbegin(), types.cend(), std::inserter(result, result.end()),
268 [](const auto &type) { return FuzzingValidatorFactory::create(type); });
268 [](const auto &type) { return FuzzingValidatorFactory::create(type); });
269
269
270 return result;
270 return result;
271 }
271 }
272
272
273 /**
273 /**
274 * Validates all the variables' states passed in parameter, according to a set of validators
274 * Validates all the variables' states passed in parameter, according to a set of validators
275 * @param variablesPool the variables' states
275 * @param variablesPool the variables' states
276 * @param validators the validators used for validation
276 * @param validators the validators used for validation
277 */
277 */
278 void validate(const VariablesPool &variablesPool, const Validators &validators)
278 void validate(const VariablesPool &variablesPool, const Validators &validators)
279 {
279 {
280 for (const auto &variablesPoolEntry : variablesPool) {
280 for (const auto &variablesPoolEntry : variablesPool) {
281 auto variableId = variablesPoolEntry.first;
281 auto variableId = variablesPoolEntry.first;
282 const auto &variableState = variablesPoolEntry.second;
282 const auto &variableState = variablesPoolEntry.second;
283
283
284 auto variableMessage = variableState.m_Variable ? variableState.m_Variable->name()
284 auto variableMessage = variableState.m_Variable ? variableState.m_Variable->name()
285 : QStringLiteral("null variable");
285 : QStringLiteral("null variable");
286 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Validating state of variable at index"
286 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Validating state of variable at index"
287 << variableId << "(" << variableMessage << ")...";
287 << variableId << "(" << variableMessage << ")...";
288
288
289 for (const auto &validator : validators) {
289 for (const auto &validator : validators) {
290 validator->validate(VariableState{variableState});
290 validator->validate(VariableState{variableState});
291 }
291 }
292
292
293 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Validation completed.";
293 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Validation completed.";
294 }
294 }
295 }
295 }
296
296
297 /**
297 /**
298 * Class to run random tests
298 * Class to run random tests
299 */
299 */
300 class FuzzingTest {
300 class FuzzingTest {
301 public:
301 public:
302 explicit FuzzingTest(VariableController &variableController, Properties properties)
302 explicit FuzzingTest(VariableController &variableController, Properties properties)
303 : m_VariableController{variableController},
303 : m_VariableController{variableController},
304 m_Properties{std::move(properties)},
304 m_Properties{std::move(properties)},
305 m_FuzzingState{}
305 m_FuzzingState{}
306 {
306 {
307 // Inits variables pool: at init, all variables are null
307 // Inits variables pool: at init, all variables are null
308 for (auto variableId = 0; variableId < nbMaxVariables(); ++variableId) {
308 for (auto variableId = 0; variableId < nbMaxVariables(); ++variableId) {
309 m_FuzzingState.m_VariablesPool[variableId] = VariableState{};
309 m_FuzzingState.m_VariablesPool[variableId] = VariableState{};
310 }
310 }
311
311
312 // Inits sync groups and registers them into the variable controller
312 // Inits sync groups and registers them into the variable controller
313 for (auto i = 0; i < nbMaxSyncGroups(); ++i) {
313 for (auto i = 0; i < nbMaxSyncGroups(); ++i) {
314 auto syncGroupId = SyncGroupId::createUuid();
314 auto syncGroupId = SyncGroupId::createUuid();
315 variableController.onAddSynchronizationGroupId(syncGroupId);
315 variableController.onAddSynchronizationGroupId(syncGroupId);
316 m_FuzzingState.m_SyncGroupsPool[syncGroupId] = SyncGroup{};
316 m_FuzzingState.m_SyncGroupsPool[syncGroupId] = SyncGroup{};
317 }
317 }
318 }
318 }
319
319
320 void execute()
320 void execute()
321 {
321 {
322
322
323 // Inits the count of the number of operations before the next validation
323 // Inits the count of the number of operations before the next validation
324 int nextValidationCounter = 0;
324 int nextValidationCounter = 0;
325 auto updateValidationCounter = [this, &nextValidationCounter]() {
325 auto updateValidationCounter = [this, &nextValidationCounter]() {
326 nextValidationCounter = RandomGenerator::instance().generateInt(
326 nextValidationCounter = RandomGenerator::instance().generateInt(
327 validationFrequencies().first, validationFrequencies().second);
327 validationFrequencies().first, validationFrequencies().second);
328 qCInfo(LOG_TestAmdaFuzzing()).noquote()
328 qCInfo(LOG_TestAmdaFuzzing()).noquote()
329 << "Next validation in " << nextValidationCounter << "operation(s)...";
329 << "Next validation in " << nextValidationCounter << "operation(s)...";
330 };
330 };
331 updateValidationCounter();
331 updateValidationCounter();
332
332
333 // Get custom operations
333 // Get custom operations
334 auto customOperations = m_Properties.value(CUSTOM_OPERATIONS_PROPERTY).value<CustomVariablesOperations>();
334 auto customOperations = m_Properties.value(CUSTOM_OPERATIONS_PROPERTY).value<CustomVariablesOperations>();
335 auto isCustomTest = !customOperations.empty();
335 auto isCustomTest = !customOperations.empty();
336
336
337 auto nbOperations = isCustomTest ? customOperations.size() : nbMaxOperations();
337 auto nbOperations = isCustomTest ? customOperations.size() : nbMaxOperations();
338
338
339 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Running" << nbOperations << "operations on"
339 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Running" << nbOperations << "operations on"
340 << nbMaxVariables() << "variable(s)...";
340 << nbMaxVariables() << "variable(s)...";
341
341
342 auto canExecute = true;
342 auto canExecute = true;
343 for (auto i = 0; i < nbOperations && canExecute; ++i) {
343 for (auto i = 0; i < nbOperations && canExecute; ++i) {
344 VariableOperation variableOperation{};
344 VariableOperation variableOperation{};
345 auto forceWait = false;
345 auto forceWait = false;
346
346
347 if(isCustomTest){
347 if(isCustomTest){
348 auto customOperation = customOperations.front();
348 auto customOperation = customOperations.front();
349 variableOperation = customOperation.m_VariableOperation;
349 variableOperation = customOperation.m_VariableOperation;
350 customOperations.erase(customOperations.begin());
350 customOperations.erase(customOperations.begin());
351
351
352 canExecute = variableOperation.second->canExecute(variableOperation.first, m_FuzzingState);
352 canExecute = variableOperation.second->canExecute(variableOperation.first, m_FuzzingState);
353 forceWait = customOperation.m_WaitAcquisition;
353 forceWait = customOperation.m_WaitAcquisition;
354 } else {
354 } else {
355 // Retrieves all operations that can be executed in the current context
355 // Retrieves all operations that can be executed in the current context
356 VariablesOperations variableOperations{};
356 VariablesOperations variableOperations{};
357 Weights weights{};
357 Weights weights{};
358 std::tie(variableOperations, weights)
358 std::tie(variableOperations, weights)
359 = availableOperations(m_FuzzingState, operationsPool());
359 = availableOperations(m_FuzzingState, operationsPool());
360
360
361 // Of the operations available, chooses a random operation and executes it
361 // Of the operations available, chooses a random operation and executes it
362 variableOperation
362 variableOperation
363 = RandomGenerator::instance().randomChoice(variableOperations, weights);
363 = RandomGenerator::instance().randomChoice(variableOperations, weights);
364 canExecute = !variableOperations.empty();
364 canExecute = !variableOperations.empty();
365 forceWait = operationsPool().at(variableOperation.second).m_WaitAcquisition;
365 forceWait = operationsPool().at(variableOperation.second).m_WaitAcquisition;
366 }
366 }
367
367
368 if (canExecute) {
368 if (canExecute) {
369 --nextValidationCounter;
369 --nextValidationCounter;
370
370
371 auto variableId = variableOperation.first;
371 auto variableId = variableOperation.first;
372 auto fuzzingOperation = variableOperation.second;
372 auto fuzzingOperation = variableOperation.second;
373
373
374 auto waitAcquisition = nextValidationCounter == 0
374 auto waitAcquisition = nextValidationCounter == 0
375 || forceWait;
375 || forceWait;
376
376
377 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Operation :" << i +1 << " on"
378 << nbOperations;
377 fuzzingOperation->execute(variableId, m_FuzzingState, m_VariableController,
379 fuzzingOperation->execute(variableId, m_FuzzingState, m_VariableController,
378 m_Properties);
380 m_Properties);
379
381
380 if (waitAcquisition) {
382 if (waitAcquisition) {
381 qCDebug(LOG_TestAmdaFuzzing()) << "Waiting for acquisition to finish...";
383 qCDebug(LOG_TestAmdaFuzzing()) << "Waiting for acquisition to finish...";
382 SignalWaiter{m_VariableController, SIGNAL(acquisitionFinished())}.wait(
384 SignalWaiter{m_VariableController, SIGNAL(acquisitionFinished())}.wait(
383 acquisitionTimeout());
385 acquisitionTimeout());
384
386
385 // Validates variables
387 // Validates variables
386 if (nextValidationCounter == 0) {
388 if (nextValidationCounter == 0) {
387 validate(m_FuzzingState.m_VariablesPool, validators());
389 validate(m_FuzzingState.m_VariablesPool, validators());
388 updateValidationCounter();
390 updateValidationCounter();
389 }
391 }
390 }
392 }
391 else {
393 else {
392 // Delays the next operation with a randomly generated time
394 // Delays the next operation with a randomly generated time
393 auto delay = RandomGenerator::instance().generateInt(operationDelays().first,
395 auto delay = RandomGenerator::instance().generateInt(operationDelays().first,
394 operationDelays().second);
396 operationDelays().second);
395 qCDebug(LOG_TestAmdaFuzzing())
397 qCDebug(LOG_TestAmdaFuzzing())
396 << "Waiting " << delay << "ms before the next operation...";
398 << "Waiting " << delay << "ms before the next operation...";
397 QTest::qWait(delay);
399 QTest::qWait(delay);
398 }
400 }
399 }
401 }
400 else {
402 else {
401 qCInfo(LOG_TestAmdaFuzzing()).noquote()
403 qCInfo(LOG_TestAmdaFuzzing()).noquote()
402 << "No more operations are available, the execution of the test will stop...";
404 << "No more operations are available, the execution of the test will stop...";
403 }
405 }
404 }
406 }
405
407
406 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Execution of the test completed.";
408 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Execution of the test completed.";
407 }
409 }
408
410
409 private:
411 private:
410 OperationsPool operationsPool() const
412 OperationsPool operationsPool() const
411 {
413 {
412 static auto result = createOperationsPool(
414 static auto result = createOperationsPool(
413 m_Properties.value(AVAILABLE_OPERATIONS_PROPERTY, AVAILABLE_OPERATIONS_DEFAULT_VALUE)
415 m_Properties.value(AVAILABLE_OPERATIONS_PROPERTY, AVAILABLE_OPERATIONS_DEFAULT_VALUE)
414 .value<OperationsTypes>());
416 .value<OperationsTypes>());
415 return result;
417 return result;
416 }
418 }
417
419
418 Validators validators() const
420 Validators validators() const
419 {
421 {
420 static auto result
422 static auto result
421 = createValidators(m_Properties.value(VALIDATORS_PROPERTY, VALIDATORS_DEFAULT_VALUE)
423 = createValidators(m_Properties.value(VALIDATORS_PROPERTY, VALIDATORS_DEFAULT_VALUE)
422 .value<ValidatorsTypes>());
424 .value<ValidatorsTypes>());
423 return result;
425 return result;
424 }
426 }
425
427
426 DECLARE_PROPERTY_GETTER(nbMaxOperations, NB_MAX_OPERATIONS, int)
428 DECLARE_PROPERTY_GETTER(nbMaxOperations, NB_MAX_OPERATIONS, int)
427 DECLARE_PROPERTY_GETTER(nbMaxSyncGroups, NB_MAX_SYNC_GROUPS, int)
429 DECLARE_PROPERTY_GETTER(nbMaxSyncGroups, NB_MAX_SYNC_GROUPS, int)
428 DECLARE_PROPERTY_GETTER(nbMaxVariables, NB_MAX_VARIABLES, int)
430 DECLARE_PROPERTY_GETTER(nbMaxVariables, NB_MAX_VARIABLES, int)
429 DECLARE_PROPERTY_GETTER(operationDelays, OPERATION_DELAY_BOUNDS, IntPair)
431 DECLARE_PROPERTY_GETTER(operationDelays, OPERATION_DELAY_BOUNDS, IntPair)
430 DECLARE_PROPERTY_GETTER(validationFrequencies, VALIDATION_FREQUENCY_BOUNDS, IntPair)
432 DECLARE_PROPERTY_GETTER(validationFrequencies, VALIDATION_FREQUENCY_BOUNDS, IntPair)
431 DECLARE_PROPERTY_GETTER(acquisitionTimeout, ACQUISITION_TIMEOUT, int)
433 DECLARE_PROPERTY_GETTER(acquisitionTimeout, ACQUISITION_TIMEOUT, int)
432
434
433 VariableController &m_VariableController;
435 VariableController &m_VariableController;
434 Properties m_Properties;
436 Properties m_Properties;
435 FuzzingState m_FuzzingState;
437 FuzzingState m_FuzzingState;
436 };
438 };
437
439
438 } // namespace
440 } // namespace
439
441
440 Q_DECLARE_METATYPE(OperationsTypes)
442 Q_DECLARE_METATYPE(OperationsTypes)
441 Q_DECLARE_METATYPE(CustomVariablesOperations)
443 Q_DECLARE_METATYPE(CustomVariablesOperations)
442
444
443 class TestAmdaFuzzing : public QObject {
445 class TestAmdaFuzzing : public QObject {
444 Q_OBJECT
446 Q_OBJECT
445
447
446 private slots:
448 private slots:
447 /// Input data for @sa testFuzzing()
449 /// Input data for @sa testFuzzing()
448 void testFuzzing_data();
450 void testFuzzing_data();
449 void testFuzzing();
451 void testFuzzing();
450 };
452 };
451
453
452 void TestAmdaFuzzing::testFuzzing_data()
454 void TestAmdaFuzzing::testFuzzing_data()
453 {
455 {
454 // Note: Comment this line to run fuzzing tests
456 // Note: Comment this line to run fuzzing tests
455 // QSKIP("Fuzzing tests are disabled by default");
457 // QSKIP("Fuzzing tests are disabled by default");
456
458
457 // ////////////// //
459 // ////////////// //
458 // Test structure //
460 // Test structure //
459 // ////////////// //
461 // ////////////// //
460
462
461 QTest::addColumn<Properties>("properties"); // Properties for random test
463 QTest::addColumn<Properties>("properties"); // Properties for random test
462
464
463 // ////////// //
465 // ////////// //
464 // Test cases //
466 // Test cases //
465 // ////////// //
467 // ////////// //
466
468
467 auto maxRange = SqpRange::fromDateTime({2017, 1, 3}, {0, 0}, {2017, 1, 5}, {0, 0});
469 auto maxRange = SqpRange::fromDateTime({2017, 1, 5}, {8, 0}, {2017, 1, 5}, {16, 0});
468 MetadataPool metadataPool{{{"dataType", "vector"}, {"xml:id", "c1_b"}}};
470 MetadataPool metadataPool{{{"dataType", "vector"}, {"xml:id", "c1_b"}}};
469
471
470 // Note: we don't use auto here as we want to pass std::shared_ptr<IDataProvider> as is in the
472 // Note: we don't use auto here as we want to pass std::shared_ptr<IDataProvider> as is in the
471 // QVariant
473 // QVariant
472 std::shared_ptr<IDataProvider> provider = std::make_shared<AmdaProvider>();
474 std::shared_ptr<IDataProvider> provider = std::make_shared<AmdaProvider>();
473
475
474
476
475 // Case Custom one : Only lot of pan on two variables synchronized
477 // Case Custom one : Only lot of pan on two variables synchronized
476 // QTest::newRow("fuzzingTestPan") << Properties{
478 // QTest::newRow("fuzzingTestPan") << Properties{
477 // {MAX_RANGE_PROPERTY, QVariant::fromValue(maxRange)},
479 // {MAX_RANGE_PROPERTY, QVariant::fromValue(maxRange)},
478 // {METADATA_POOL_PROPERTY, QVariant::fromValue(metadataPool)},
480 // {METADATA_POOL_PROPERTY, QVariant::fromValue(metadataPool)},
479 // {PROVIDER_PROPERTY, QVariant::fromValue(provider)},
481 // {PROVIDER_PROPERTY, QVariant::fromValue(provider)},
480 // {CUSTOM_OPERATIONS_PROPERTY, CUSTOM_CASE_ONE}};
482 // {CUSTOM_OPERATIONS_PROPERTY, CUSTOM_CASE_ONE}};
481
483
482 QTest::newRow("fuzzingTestZoom") << Properties{
484 // QTest::newRow("fuzzingTestZoom") << Properties{
483 {MAX_RANGE_PROPERTY, QVariant::fromValue(maxRange)},
485 // {MAX_RANGE_PROPERTY, QVariant::fromValue(maxRange)},
484 {METADATA_POOL_PROPERTY, QVariant::fromValue(metadataPool)},
486 // {METADATA_POOL_PROPERTY, QVariant::fromValue(metadataPool)},
485 {PROVIDER_PROPERTY, QVariant::fromValue(provider)},
487 // {PROVIDER_PROPERTY, QVariant::fromValue(provider)},
486 {CUSTOM_OPERATIONS_PROPERTY, CUSTOM_CASE_TWO}};
488 // {CUSTOM_OPERATIONS_PROPERTY, CUSTOM_CASE_TWO}};
487
489
488
490
489 //// Fuzzing
491 //// Fuzzing
490 // QTest::newRow("fuzzingTest") << Properties{
492 QTest::newRow("fuzzingTest") << Properties{
491 // {MAX_RANGE_PROPERTY, QVariant::fromValue(maxRange)},
493 {MAX_RANGE_PROPERTY, QVariant::fromValue(maxRange)},
492 // {METADATA_POOL_PROPERTY, QVariant::fromValue(metadataPool)},
494 {METADATA_POOL_PROPERTY, QVariant::fromValue(metadataPool)},
493 // {PROVIDER_PROPERTY, QVariant::fromValue(provider)}};
495 {PROVIDER_PROPERTY, QVariant::fromValue(provider)}};
494
496
495 }
497 }
496
498
497 void TestAmdaFuzzing::testFuzzing()
499 void TestAmdaFuzzing::testFuzzing()
498 {
500 {
499 QFETCH(Properties, properties);
501 QFETCH(Properties, properties);
500
502
501 // Sets cache property
503 // Sets cache property
502 QSettings settings{};
504 QSettings settings{};
503 auto cacheTolerance = properties.value(CACHE_TOLERANCE_PROPERTY, CACHE_TOLERANCE_DEFAULT_VALUE);
505 auto cacheTolerance = properties.value(CACHE_TOLERANCE_PROPERTY, CACHE_TOLERANCE_DEFAULT_VALUE);
504 settings.setValue(GENERAL_TOLERANCE_AT_INIT_KEY, cacheTolerance);
506 settings.setValue(GENERAL_TOLERANCE_AT_INIT_KEY, cacheTolerance);
505 settings.setValue(GENERAL_TOLERANCE_AT_UPDATE_KEY, cacheTolerance);
507 settings.setValue(GENERAL_TOLERANCE_AT_UPDATE_KEY, cacheTolerance);
506
508
507 auto &variableController = sqpApp->variableController();
509 auto &variableController = sqpApp->variableController();
508 auto &timeController = sqpApp->timeController();
510 auto &timeController = sqpApp->timeController();
509
511
510 // Generates random initial range (bounded to max range)
512 // Generates random initial range (bounded to max range)
511 auto maxRange = properties.value(MAX_RANGE_PROPERTY, QVariant::fromValue(INVALID_RANGE))
513 auto maxRange = properties.value(MAX_RANGE_PROPERTY, QVariant::fromValue(INVALID_RANGE))
512 .value<SqpRange>();
514 .value<SqpRange>();
513
515
514 QVERIFY(maxRange != INVALID_RANGE);
516 QVERIFY(maxRange != INVALID_RANGE);
515
517
516 auto initialRangeStart
518 auto initialRangeStart
517 = RandomGenerator::instance().generateDouble(maxRange.m_TStart, maxRange.m_TEnd);
519 = RandomGenerator::instance().generateDouble(maxRange.m_TStart, maxRange.m_TEnd);
518 auto initialRangeEnd
520 auto initialRangeEnd
519 = RandomGenerator::instance().generateDouble(maxRange.m_TStart, maxRange.m_TEnd);
521 = RandomGenerator::instance().generateDouble(maxRange.m_TStart, maxRange.m_TEnd);
520 if (initialRangeStart > initialRangeEnd) {
522 if (initialRangeStart > initialRangeEnd) {
521 std::swap(initialRangeStart, initialRangeEnd);
523 std::swap(initialRangeStart, initialRangeEnd);
522 }
524 }
523
525
524 // Sets initial range on time controller
526 // Sets initial range on time controller
525 SqpRange initialRange{initialRangeStart, initialRangeEnd};
527 SqpRange initialRange{initialRangeStart, initialRangeEnd};
526 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Setting initial range to" << initialRange << "...";
528 qCInfo(LOG_TestAmdaFuzzing()).noquote() << "Setting initial range to" << initialRange << "...";
527 timeController.onTimeToUpdate(initialRange);
529 timeController.onTimeToUpdate(initialRange);
528 properties.insert(INITIAL_RANGE_PROPERTY, QVariant::fromValue(initialRange));
530 properties.insert(INITIAL_RANGE_PROPERTY, QVariant::fromValue(initialRange));
529
531
530 FuzzingTest test{variableController, properties};
532 FuzzingTest test{variableController, properties};
531 test.execute();
533 test.execute();
532 }
534 }
533
535
534 int main(int argc, char *argv[])
536 int main(int argc, char *argv[])
535 {
537 {
536 // Increases the test function timeout (which is 5 minutes by default) to 12 hours
538 // Increases the test function timeout (which is 5 minutes by default) to 12 hours
537 // https://stackoverflow.com/questions/42655932/setting-timeout-to-qt-test
539 // https://stackoverflow.com/questions/42655932/setting-timeout-to-qt-test
538 qputenv("QTEST_FUNCTION_TIMEOUT", QByteArray::number(12*60*60*1000));
540 qputenv("QTEST_FUNCTION_TIMEOUT", QByteArray::number(12*60*60*1000));
539
541
540 QLoggingCategory::setFilterRules(
542 QLoggingCategory::setFilterRules(
541 "*.warning=false\n"
543 "*.warning=false\n"
542 "*.info=false\n"
544 "*.info=false\n"
543 "*.debug=false\n"
545 "*.debug=false\n"
544 "FuzzingOperations.info=true\n"
546 "FuzzingOperations.info=true\n"
545 "FuzzingValidators.info=true\n"
547 "FuzzingValidators.info=true\n"
546 "TestAmdaFuzzing.info=true\n");
548 "TestAmdaFuzzing.info=true\n");
547
549
548 SqpApplication app{argc, argv};
550 SqpApplication app{argc, argv};
549 SqpApplication::setOrganizationName("LPP");
551 SqpApplication::setOrganizationName("LPP");
550 SqpApplication::setOrganizationDomain("lpp.fr");
552 SqpApplication::setOrganizationDomain("lpp.fr");
551 SqpApplication::setApplicationName("SciQLop-TestFuzzing");
553 SqpApplication::setApplicationName("SciQLop-TestFuzzing");
552 app.setAttribute(Qt::AA_Use96Dpi, true);
554 app.setAttribute(Qt::AA_Use96Dpi, true);
553 TestAmdaFuzzing testObject{};
555 TestAmdaFuzzing testObject{};
554 QTEST_SET_MAIN_SOURCE_PATH
556 QTEST_SET_MAIN_SOURCE_PATH
555 return QTest::qExec(&testObject, argc, argv);
557 return QTest::qExec(&testObject, argc, argv);
556 }
558 }
557
559
558 #include "TestAmdaFuzzing.moc"
560 #include "TestAmdaFuzzing.moc"
General Comments 0
You need to be logged in to leave comments. Login now