Dawn Framework 1.0
Universal data acquisition framework for embedded systems
sampling.cxx
1// dawn/src/prog/sampling.cxx
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5
6#include "dawn/prog/sampling.hxx"
7
8#include <new>
9#include <sched.h>
10#include <time.h>
11
12#include "dawn/debug.hxx"
13#include "dawn/io/common.hxx"
14#include "dawn/io/ddata.hxx"
15
16using namespace dawn;
17
18int CProgSampling::configureDesc(const CDescObject &desc)
19{
20 const SObjectCfg::SObjectCfgItem *item = nullptr;
21 const SObjectId::UObjectId *ids;
22 const uint32_t *data;
23 size_t offset = 0;
24 size_t nbind;
25 size_t j;
26 int ret;
27
28 for (size_t i = 0; i < desc.getSize(); i++)
29 {
30 item = desc.objectCfgItemNext(offset);
31
33 {
34 DAWNERR("Unsupported sampling config 0x%08" PRIx32 "\n", item->cfgid.v);
35 return -EINVAL;
36 }
37
38 switch (item->cfgid.s.id)
39 {
41 {
42 if (item->cfgid.s.size % 2 != 0)
43 {
44 DAWNERR("Invalid IOBIND size %d, must be even\n", item->cfgid.s.size);
45 return -EINVAL;
46 }
47
48 nbind = item->cfgid.s.size / 2;
49 ids = reinterpret_cast<const SObjectId::UObjectId *>(item->data);
50
51 for (j = 0; j < nbind; j++)
52 {
53 ret = allocObject(ids[j * 2].v, ids[j * 2 + 1].v);
54 if (ret != OK)
55 {
56 return ret;
57 }
58 }
59
60 break;
61 }
62
64 {
65 if (item->cfgid.s.size != 1)
66 {
67 DAWNERR("Invalid INTERVAL size %d\n", item->cfgid.s.size);
68 return -EINVAL;
69 }
70
71 data = reinterpret_cast<const uint32_t *>(item->data);
72 interval = *data;
73 break;
74 }
75
77 {
78 if (item->cfgid.s.size != 1)
79 {
80 DAWNERR("Invalid PRIORITY size %d\n", item->cfgid.s.size);
81 return -EINVAL;
82 }
83
84 priority = static_cast<int>(item->data[0]);
85 break;
86 }
87
89 {
90 if (item->cfgid.s.size != 1 || (item->data[0] & ~FLAG_AUTO_START) != 0)
91 {
92 DAWNERR("Invalid FLAGS item\n");
93 return -EINVAL;
94 }
95
96 flags = item->data[0];
97 break;
98 }
99
100 default:
101 {
102 DAWNERR("Unsupported sampling config 0x%08" PRIx32 "\n", item->cfgid.v);
103 return -EINVAL;
104 }
105 }
106 }
107
108 return OK;
109}
110
111int CProgSampling::allocObject(SObjectId::ObjectId srcId, SObjectId::ObjectId targetId)
112{
113 SSamplingBind *b;
114
115 DAWNINFO("allocate sampling 0x%" PRIx32 " -> 0x%" PRIx32 "\n", srcId, targetId);
116
117 b = new (std::nothrow) SSamplingBind();
118 if (!b)
119 {
120 return -ENOMEM;
121 }
122
123 b->srcId = srcId;
124 b->targetId = targetId;
125 b->src = nullptr;
126 b->target = nullptr;
127 b->iodata = nullptr;
128
129 setObjectMapItem(b->srcId, nullptr);
130 setObjectMapItem(b->targetId, nullptr);
131 binds.push_back(b);
132
133 return OK;
134}
135
136int CProgSampling::onSetObjConfig(SObjectCfg::ObjectCfgId objcfg, uint32_t *data, size_t len)
137{
139 {
140 return OK;
141 }
142
143 if (data == nullptr || len != 1)
144 {
145 return -EINVAL;
146 }
147
148 interval = *data;
149 return OK;
150}
151
152// Advance an absolute deadline by us microseconds
153
154static void deadlineAdd(struct timespec &ts, uint32_t us)
155{
156 ts.tv_nsec += static_cast<long>(us % 1000000) * 1000L;
157 ts.tv_sec += us / 1000000 + ts.tv_nsec / 1000000000L;
158 ts.tv_nsec %= 1000000000L;
159}
160
161void CProgSampling::thread()
162{
163 SSamplingBind *b;
164 struct timespec next;
165 struct timespec now;
166 uint32_t period;
167 bool armed = false;
168 size_t i;
169 int ret;
170
171 DAWNINFO("start sampling thread\n");
172
173 do
174 {
175 // Stopped by trigger: wait without sampling until started again
176
177 if (!active)
178 {
179 armed = false;
180 sem_wait(&wakeup);
181 if (stopping)
182 {
183 break;
184 }
185
186 continue;
187 }
188
189 period = interval;
190 if (period != 0 && !armed)
191 {
192 clock_gettime(CLOCK_MONOTONIC, &next);
193 armed = true;
194 }
195
196 // Sample all source IOs and push to targets
197
198 for (i = 0; i < binds.size(); i++)
199 {
200 b = binds[i];
201
202 ret = b->src->getData(*b->iodata, 1);
203 if (ret != OK)
204 {
205 DAWNERR("getData failed for src %zu (error %d)\n", i, ret);
206 continue;
207 }
208
209 ret = b->target->setData(*b->iodata);
210 if (ret != OK)
211 {
212 DAWNERR("setData failed for target %zu (error %d)\n", i, ret);
213 }
214 }
215
216 // Zero samples back to back, for sources whose read blocks
217
218 if (period == 0)
219 {
220 armed = false;
221 sched_yield();
222 continue;
223 }
224
225 // Deadlines step by the interval, so sampling work and timer rounding
226 // do not stretch the period. A late sample is caught up on the next
227 // wakeup; only a stall of a second or more restarts the schedule.
228
229 deadlineAdd(next, period);
230 clock_gettime(CLOCK_MONOTONIC, &now);
231 if (now.tv_sec > next.tv_sec + 1 ||
232 (now.tv_sec == next.tv_sec + 1 && now.tv_nsec > next.tv_nsec))
233 {
234 next = now;
235 }
236
237 clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, nullptr);
238 }
239 while (!threadCtl.shouldQuit());
240}
241
242CProgSampling::~CProgSampling()
243{
244 deinit();
245 sem_destroy(&wakeup);
246}
247
249{
250 int ret;
251
252 // Configure object
253
254 ret = configureDesc(getDesc());
255 if (ret != OK)
256 {
257 DAWNERR("Sampling configure failed (error %d)\n", ret);
258 return ret;
259 }
260
261 // One-time initialization that depends on bindings is done in init()
262
263 return OK;
264}
265
267{
268 size_t i;
269
270 // Free allocated data buffers
271
272 for (i = 0; i < binds.size(); i++)
273 {
274 delete binds[i]->iodata;
275 delete binds[i];
276 }
277
278 binds.clear();
279
280 return OK;
281}
282
284{
285 SSamplingBind *b;
286 size_t i;
287 int ret;
288
289 // Resolve IOs, initialize writable targets, allocate buffers
290
291 for (i = 0; i < binds.size(); i++)
292 {
293 b = binds[i];
294
295 b->src = getIO(b->srcId);
296 if (!b->src)
297 {
298 DAWNERR("Source IO 0x%" PRIx32 " not found\n", b->srcId);
299 return -EIO;
300 }
301
302 if (!b->src->isRead())
303 {
304 DAWNERR("Source IO 0x%" PRIx32 " is not readable\n", b->srcId);
305 return -EINVAL;
306 }
307
308 b->target = getIO(b->targetId);
309 if (!b->target)
310 {
311 DAWNERR("Target IO 0x%" PRIx32 " not found\n", b->targetId);
312 return -EIO;
313 }
314
315 if (b->target->getDtype() != b->src->getDtype())
316 {
317 DAWNERR("Target IO 0x%" PRIx32 " dtype mismatch\n", b->targetId);
318 return -EINVAL;
319 }
320
321 // Initialize deferred virtual targets and validate configured targets
322
323 ret = prepareWritableTarget(b->target,
324 b->src->getDataDim(),
325#ifdef CONFIG_DAWN_IO_NOTIFY
326 true
327#else
328 false
329#endif
330 );
331 if (ret != OK)
332 {
333 DAWNERR("Failed to initialize target %zu (error %d)\n", i, ret);
334 return ret;
335 }
336
337 if (b->target->getDataDim() != b->src->getDataDim() ||
338 b->target->getDataSize() != b->src->getDataSize())
339 {
340 DAWNERR("Target IO 0x%" PRIx32 " shape mismatch\n", b->targetId);
341 return -EINVAL;
342 }
343
344 // Allocate data buffer for this source
345
346 b->iodata = b->src->ddata_alloc(1);
347 if (!b->iodata)
348 {
349 DAWNERR("Failed to allocate data buffer for src %zu\n", i);
350 return -ENOMEM;
351 }
352 }
353
354 return OK;
355}
356
358{
359 // Drop wakeups left from the previous run
360
361 while (sem_trywait(&wakeup) == 0)
362 {
363 }
364
365 active = (flags & FLAG_AUTO_START) != 0;
366 stopping = false;
367
368 // Start sampling thread
369
370 threadCtl.setThreadPriority(priority);
371 threadCtl.setThreadFunc([this]() { thread(); });
372 return threadCtl.threadStart();
373}
374
376{
377 // Wake the thread if it waits for a trigger
378
379 stopping = true;
380 sem_post(&wakeup);
381 return threadCtl.threadStop();
382}
383
385{
386 switch (cmd)
387 {
388 case CMD_TRIGGER1:
389 active = true;
390 sem_post(&wakeup);
391 return OK;
392
393 case CMD_TRIGGER2:
394 active = false;
395 return OK;
396
397 default:
398 return -ENOTSUP;
399 }
400}
401
403{
404 return threadCtl.isRunning();
405}
CIOCommon * getIO(SObjectId::ObjectId id)
Get an I/O object by ID.
Definition bindable.cxx:41
void setObjectMapItem(SObjectId::ObjectId id, CObject *obj)
Set an item in the object map.
Definition bindable.cxx:23
Descriptor wrapper for individual object configuration.
size_t getSize() const
Get number of configuration items for this object.
SObjectCfg::SObjectCfgItem * objectCfgItemNext(size_t &offset) const
Get config item at current offset and advance past it.
virtual size_t getDataDim() const =0
Get data vector dimension.
io_ddata_t * ddata_alloc(size_t batch, size_t chunk_size=0)
Allocate data buffer for this I/O.
Definition common.cxx:249
virtual size_t getDataSize() const =0
Get data size in bytes.
virtual bool isRead() const =0
Check if IO supports read operations.
@ CMD_TRIGGER2
Object-specific trigger slot 2.
Definition object.hxx:44
@ CMD_TRIGGER1
Object-specific trigger slot 1.
Definition object.hxx:43
CDescObject & getDesc()
Get descriptor object for this object.
Definition object.cxx:190
uint8_t getDtype() const
Get data type field.
Definition object.cxx:175
int prepareWritableTarget(CIOCommon *io, size_t dim, bool notify, size_t batch=1)
Check a writable output; shape a deferred virt output or check an already shaped one.
Definition common.cxx:45
@ PROG_CLASS_SAMPLING
Periodic data sampler.
Definition common.hxx:64
int trigger(uint8_t cmd)
Execute a trigger command.
Definition sampling.cxx:384
int doStart()
Start implementation hook.
Definition sampling.cxx:357
bool hasThread() const
Check if a background thread is active.
Definition sampling.cxx:402
@ FLAG_AUTO_START
Sample from start, without a trigger.
Definition sampling.hxx:47
int configure()
Configure object from descriptor data.
Definition sampling.cxx:248
int onSetObjConfig(SObjectCfg::ObjectCfgId objcfg, uint32_t *data, size_t len)
Pre-update hook for runtime configuration writes.
Definition sampling.cxx:136
int init()
One-time initialize object after bindings are resolved.
Definition sampling.cxx:283
int doStop()
Stop implementation hook.
Definition sampling.cxx:375
int deinit()
De-initialize object.
Definition sampling.cxx:266
@ PROG_SAMPLING_CFG_INTERVAL
Sampling interval (microseconds).
Definition sampling.hxx:39
@ PROG_SAMPLING_CFG_IOBIND
I/O binding configuration.
Definition sampling.hxx:38
@ PROG_SAMPLING_CFG_PRIORITY
Sampling thread priority (0 = default).
Definition sampling.hxx:40
@ PROG_SAMPLING_CFG_FLAGS
Behavior flags.
Definition sampling.hxx:41
uint32_t ObjectCfgId
ConfigID type - single 32-bit value.
Definition objectcfg.hxx:60
static uint8_t objectCfgGetId(const ObjectCfgId objcfg)
Extract configuration identifier from ConfigID.
Out-of-tree user-extension hooks for Dawn.
Definition bindable.hxx:13
ObjectCfgData_t data[]
Configuration data array (flexible, size from cfgid.s.size).
UObjectCfgId cfgid
Configuration ID header (type, class, id, size, rw, dtype).
uint32_t ObjectId
ObjectID type - single 32-bit value.
Definition objectid.hxx:44
ObjectCfgId v
Raw 32-bit ConfigID value (for storage, comparison).
Definition objectcfg.hxx:82
uint32_t cls
Object class (bits 21-29, max 511).
uint32_t id
Configuration identifier (bits 0-4, max 31).
Definition objectcfg.hxx:94
struct dawn::SObjectCfg::UObjectCfgId::@334307326077356333363326153167141302007100111136 s
Bit-field structure for named member access.
uint32_t size
Configuration data size in 32-bit words (bits 5-14, max 1023).