Repository navigation
Expand file tree
/
Copy pathProcessModel.h
More file actions
304 lines (255 loc) · 9.48 KB
/
Copy pathProcessModel.h
File metadata and controls
304 lines (255 loc) · 9.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright 2024-2026 Board of Regents of the University of Wisconsin System
// SPDX-License-Identifier: BSD-2-Clause
#pragma once
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstddef>
#include <functional>
#include <mutex>
#include <numeric>
#include <thread>
#include <utility>
// Models of physical device state. SyncProcessModel and AsyncProcessModel have
// the same compile-time interface.
//
// SyncProcessModel issues change notifications synchronously (i.e., from the
// thread setting the value) and never becomes busy. Its member functions are
// not thread-safe: they must be called with external synchronization.
//
// AsyncProcessModel separates setpoint from process variable; the latter is
// slewed so that it reaches the setpoint over time (so the model is "busy"
// while still slewing). Change notifications are periodically issued from a
// background thread during the slewing, with the last notification always
// occuring when the PV reaches the SP. The mutating member functions
// (Setpoint(value), Halt(), and the rate/interval setters) must be called with
// external synchronization; ProcessVariable(), Setpoint(), and IsSlewing() may
// be called from any thread.
template <std::size_t Dim> class SyncProcessModel {
using ValueType = std::array<double, Dim>;
// Setpoint and process variable are always equal.
ValueType value_{};
std::function<void(ValueType)> update_;
ValueType lastUpdatedPV_{};
void Update() {
if (value_ == lastUpdatedPV_) {
return;
}
update_(value_);
lastUpdatedPV_ = value_;
}
public:
static constexpr bool isAsync = false;
explicit SyncProcessModel(std::function<void(ValueType)> updateFunc)
: update_(std::move(updateFunc)) {
assert(update_);
}
void ReciprocalSlewRateSeconds(double rRate_s) {
(void)rRate_s;
assert(false);
}
double ReciprocalSlewRateSeconds() const {
assert(false);
return 1.0;
}
void UpdateIntervalSeconds(double interval_s) {
(void)interval_s;
assert(false);
}
double UpdateIntervalSeconds() const {
assert(false);
return 0.1;
}
bool IsSlewing() const { return false; }
ValueType ProcessVariable() const { return value_; }
ValueType Setpoint() const { return value_; }
void Halt() { /* no-op */ }
void Setpoint(ValueType setpoint) {
assert(std::all_of(setpoint.cbegin(), setpoint.cend(),
[](double v) { return std::isfinite(v); }));
value_ = setpoint;
Update();
}
};
template <std::size_t Dim> class SlewModel {
static_assert(Dim > 0, "Cannot handle empty value type");
using ValueType = std::array<double, Dim>;
ValueType origin_;
ValueType target_;
ValueType displacement_;
std::array<std::chrono::duration<double>, Dim> rRate_;
std::chrono::duration<double> duration_;
std::chrono::steady_clock::time_point startTime_;
decltype(startTime_ + duration_) finishTime_;
public:
explicit SlewModel(ValueType origin, ValueType target,
std::chrono::duration<double> absRRate)
: origin_(origin), target_(target), displacement_([this] {
ValueType d;
std::transform(target_.cbegin(), target_.cend(),
origin_.cbegin(), d.begin(),
[](auto a, auto b) { return a - b; });
return d;
}()),
rRate_([this, absRRate] {
decltype(rRate_) rr;
std::transform(displacement_.cbegin(), displacement_.cend(),
rr.begin(), [absRRate](auto d) {
return d < 0.0 ? -absRRate : absRRate;
});
return rr;
}()),
duration_([this] {
std::array<std::chrono::duration<double>, Dim> dur;
std::transform(displacement_.cbegin(), displacement_.cend(),
rRate_.cbegin(), dur.begin(),
[](auto disp, auto rr) { return disp * rr; });
return *std::max_element(dur.cbegin(), dur.cend());
}()),
startTime_(std::chrono::steady_clock::now()),
finishTime_(startTime_ + duration_) {}
ValueType Origin() const { return origin_; }
ValueType Target() const { return target_; }
auto StartTime() const { return startTime_; }
auto FinishTime() const { return finishTime_; }
template <typename TimePoint> ValueType ValueAtTime(TimePoint tp) const {
const auto elapsed = tp - startTime_;
auto elemAtTime = [this, elapsed](std::size_t i) {
const double v = origin_[i] + elapsed / rRate_[i];
if ((rRate_[i].count() > 0.0 && v > target_[i]) ||
(rRate_[i].count() < 0.0 && v < target_[i])) {
return target_[i];
}
return v;
};
std::array<std::size_t, Dim> indices;
std::iota(indices.begin(), indices.end(), 0);
ValueType value;
std::transform(indices.cbegin(), indices.cend(), value.begin(),
elemAtTime);
return value;
}
};
template <std::size_t Dim> class AsyncProcessModel {
using ValueType = std::array<double, Dim>;
std::chrono::duration<double> rRate_{1.0}; // Reciprocal rate, per PV unit
std::chrono::duration<double> updateInterval_{0.1};
// PV and SP protected by mut_ unless slewThread_ known not to be running
mutable std::mutex mut_;
ValueType procVar_{};
ValueType setpoint_{};
std::thread slewThread_;
std::mutex stopMut_;
std::condition_variable stopCv_;
bool stopRequested_ = false;
std::mutex updateMut_;
std::function<void(ValueType)> update_;
ValueType lastUpdatedPV_{};
// Only call from slew thread; cancel triggered by Halt()
template <typename TimePoint> bool CancelableWaitUntil(TimePoint timeout) {
std::unique_lock<std::mutex> lock(stopMut_);
stopCv_.wait_until(lock, timeout, [&] { return stopRequested_; });
return stopRequested_;
}
// Only call from slew thread
void Update() {
std::lock_guard<std::mutex> lock(updateMut_);
if (procVar_ == lastUpdatedPV_) {
return;
}
update_(procVar_);
lastUpdatedPV_ = procVar_;
}
public:
static constexpr bool isAsync = true;
explicit AsyncProcessModel(std::function<void(ValueType)> updateFunc)
: update_(std::move(updateFunc)) {
assert(update_);
}
~AsyncProcessModel() {
// Avoid sending updates upon halting
{
std::lock_guard<std::mutex> lock(updateMut_);
update_ = [](auto) {};
}
Halt();
}
// Set slew rate (as reciprocal slew rate); applies to next setpoint
void ReciprocalSlewRateSeconds(double rRate_s) {
assert(rRate_s > 0.0);
rRate_ = std::chrono::duration<double>{rRate_s};
}
double ReciprocalSlewRateSeconds() const { return rRate_.count(); }
// Set update interval; applies to next setpoint
void UpdateIntervalSeconds(double interval_s) {
assert(interval_s > 0.0);
updateInterval_ = std::chrono::duration<double>{interval_s};
}
double UpdateIntervalSeconds() const { return updateInterval_.count(); }
bool IsSlewing() const { // Aka "busy", "in motion"
std::lock_guard<std::mutex> lock(mut_);
return procVar_ != setpoint_;
}
ValueType ProcessVariable() const {
std::lock_guard<std::mutex> lock(mut_);
return procVar_;
}
ValueType Setpoint() const {
std::lock_guard<std::mutex> lock(mut_);
return setpoint_;
}
void Halt() {
if (!slewThread_.joinable()) {
return;
}
{
std::lock_guard<std::mutex> lock(stopMut_);
stopRequested_ = true;
}
stopCv_.notify_one();
slewThread_.join();
std::lock_guard<std::mutex> lock(mut_);
setpoint_ = procVar_;
}
void Setpoint(ValueType setpoint) {
assert(std::all_of(setpoint.cbegin(), setpoint.cend(),
[](double v) { return std::isfinite(v); }));
Halt(); // Cancel previous slew, if any, updating last PV
{
std::lock_guard<std::mutex> lock(mut_);
setpoint_ = setpoint;
}
if (procVar_ == setpoint) {
return;
}
const auto slew = SlewModel<Dim>(procVar_, setpoint, rRate_);
stopRequested_ = false;
slewThread_ = std::thread([this, slew, dt = updateInterval_] {
auto updateTime = slew.StartTime() + dt;
for (;;) {
if (slew.FinishTime() <= updateTime) {
if (!CancelableWaitUntil(slew.FinishTime())) {
std::lock_guard<std::mutex> lock(mut_);
procVar_ = slew.Target();
}
Update();
return;
}
if (CancelableWaitUntil(updateTime)) {
Update();
return;
}
const auto pv = slew.ValueAtTime(updateTime);
{
std::lock_guard<std::mutex> lock(mut_);
procVar_ = pv;
}
Update();
updateTime += dt;
}
});
}
};