forked from wirenboard/wb-mqtt-serial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserial_client.cpp
384 lines (332 loc) · 11.9 KB
/
serial_client.cpp
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#include <unistd.h>
#include <unordered_map>
#include <iostream>
#include "serial_client.h"
namespace {
struct TSerialPollEntry: public TPollEntry {
TSerialPollEntry(PRegisterRange range) {
Ranges.push_back(range);
}
std::chrono::milliseconds PollInterval() const {
return Ranges.front()->PollInterval();
}
std::list<PRegisterRange> Ranges;
};
typedef std::shared_ptr<TSerialPollEntry> PSerialPollEntry;
};
TSerialClient::TSerialClient(PPort port)
: Port(port),
Active(false),
ReadCallback([](PRegister, bool){}),
ErrorCallback([](PRegister, bool){}),
FlushNeeded(new TBinarySemaphore),
Plan(std::make_shared<TPollPlan>([this]() { return Port->CurrentTime(); })) {}
TSerialClient::~TSerialClient()
{
if (Active)
Disconnect();
// remove all registered devices
for (auto &dev : DevicesList)
TSerialDeviceFactory::RemoveDevice(dev);
}
PSerialDevice TSerialClient::CreateDevice(PDeviceConfig device_config)
{
if (Active)
throw TSerialDeviceException("can't add registers to the active client");
if (Debug)
std::cerr << "CreateDevice: " << device_config->Id <<
(device_config->DeviceType.empty() ? "" : " (" + device_config->DeviceType + ")") <<
" @ " << device_config->SlaveId << " -- protocol: " << device_config->Protocol << std::endl;
try {
PSerialDevice dev = TSerialDeviceFactory::CreateDevice(device_config, Port);
DevicesList.push_back(dev);
return dev;
} catch (const TSerialDeviceException& e) {
Disconnect();
throw;
}
}
void TSerialClient::AddRegister(PRegister reg)
{
if (Active)
throw TSerialDeviceException("can't add registers to the active client");
if (Handlers.find(reg) != Handlers.end())
throw TSerialDeviceException("duplicate register");
auto handler = Handlers[reg] = std::make_shared<TRegisterHandler>(reg->Device(), reg, FlushNeeded, Debug);
RegList.push_back(reg);
if (Debug)
std::cerr << "AddRegister: " << reg << std::endl;
}
void TSerialClient::Connect()
{
if (Active)
return;
if (!Handlers.size())
throw TSerialDeviceException("no registers defined");
if (!Port->IsOpen())
Port->Open();
PrepareRegisterRanges();
Active = true;
}
void TSerialClient::Disconnect()
{
if (Port->IsOpen())
Port->Close();
Active = false;
}
void TSerialClient::PrepareRegisterRanges()
{
// all of this is seemingly slow but it's actually only done once
Plan->Reset();
PSerialDevice last_device(0);
std::list<PRegister> cur_regs;
auto it = RegList.begin();
std::list<PSerialPollEntry> entries;
std::unordered_map<long long, PSerialPollEntry> interval_map;
for (;;) {
bool at_end = it == RegList.end();
if ((at_end || (*it)->Device() != last_device) && !cur_regs.empty()) {
cur_regs.sort([](const PRegister& a, const PRegister& b) {
return a->Type < b->Type || (a->Type == b->Type && a->Address < b->Address);
});
interval_map.clear();
// Join multiple ranges with same poll period into a
// single scheduling entry. This is necessary because
// switching between devices may require extra
// delays. This is far from being an ideal solution
// though.
for (auto range: last_device->SplitRegisterList(cur_regs)) {
PSerialPollEntry entry;
long long interval = range->PollInterval().count();
auto it = interval_map.find(interval);
if (it == interval_map.end()) {
entry = std::make_shared<TSerialPollEntry>(range);
interval_map[interval] = entry;
Plan->AddEntry(entry);
} else
it->second->Ranges.push_back(range);
}
cur_regs.clear();
}
if (at_end)
break;
last_device = (*it)->Device();
cur_regs.push_back(*it++);
}
}
void TSerialClient::SplitRegisterRanges(std::set<PRegisterRange> && ranges)
{
if (ranges.empty()) {
return;
}
Plan->Modify([&](const PPollEntry & entry){
if (auto serial_entry = std::dynamic_pointer_cast<TSerialPollEntry>(entry)) {
for (auto itRange = serial_entry->Ranges.begin(); itRange != serial_entry->Ranges.end();) {
if (ranges.count(*itRange)) {
auto device = (*itRange)->Device();
std::cerr << "Disabling holes feature for register range" << std::endl;
auto newRanges = device->SplitRegisterList((*itRange)->RegisterList(), false);
serial_entry->Ranges.insert(itRange, newRanges.begin(), newRanges.end());
ranges.erase(*itRange);
itRange = serial_entry->Ranges.erase(itRange);
} else {
++itRange;
}
}
}
return ranges.empty();
});
}
void TSerialClient::MaybeUpdateErrorState(PRegister reg, TRegisterHandler::TErrorState state)
{
if (state != TRegisterHandler::UnknownErrorState && state != TRegisterHandler::ErrorStateUnchanged)
ErrorCallback(reg, state);
}
void TSerialClient::DoFlush()
{
for (const auto& reg: RegList) {
auto handler = Handlers[reg];
if (!handler->NeedToFlush())
continue;
PrepareToAccessDevice(handler->Device());
MaybeUpdateErrorState(reg, handler->Flush());
}
}
void TSerialClient::WaitForPollAndFlush()
{
// When it's time for a next poll, take measures
// to avoid poll starvation
if (Plan->PollIsDue()) {
MaybeFlushAvoidingPollStarvationButDontWait();
return;
}
auto wait_until = Plan->GetNextPollTimePoint();
while (Port->Wait(FlushNeeded, wait_until)) {
// Don't hold the lock while flushing
DoFlush();
if (Plan->PollIsDue()) {
MaybeFlushAvoidingPollStarvationButDontWait();
return;
}
}
}
void TSerialClient::MaybeFlushAvoidingPollStarvationButDontWait()
{
// avoid poll starvation
int flush_count_remaining = MAX_FLUSHES_WHEN_POLL_IS_DUE;
while (flush_count_remaining-- && FlushNeeded->TryWait())
DoFlush();
}
void TSerialClient::PollRange(PRegisterRange range)
{
PSerialDevice dev = range->Device();
PrepareToAccessDevice(dev);
dev->ReadRegisterRange(range);
range->MapRange([this, &range](PRegister reg, uint64_t new_value) {
bool changed;
auto handler = Handlers[reg];
if (handler->NeedToPoll()) {
MaybeUpdateErrorState(reg, handler->AcceptDeviceValue(new_value, true, &changed));
// Note that handler->CurrentErrorState() is not the
// same as the value returned by handler->AcceptDeviceValue(...),
// because the latter may be ErrorStateUnchanged.
if (handler->CurrentErrorState() != TRegisterHandler::ReadError &&
handler->CurrentErrorState() != TRegisterHandler::ReadWriteError)
ReadCallback(reg, changed);
}
}, [this, &range](PRegister reg) {
bool changed;
auto handler = Handlers[reg];
if (handler->NeedToPoll())
// TBD: separate AcceptDeviceReadError method (changed is unused here)
MaybeUpdateErrorState(reg, handler->AcceptDeviceValue(0, false, &changed));
});
}
void TSerialClient::Cycle()
{
Connect();
Port->CycleBegin();
WaitForPollAndFlush();
// devices whose registers were polled during this cycle and statues
std::map<PSerialDevice, std::set<TRegisterRange::EStatus>> devicesRangesStatuses;
// ranges that needs to split
std::set<PRegisterRange> rangesToSplit;
Plan->ProcessPending([&](const PPollEntry& entry) {
for (auto range: std::dynamic_pointer_cast<TSerialPollEntry>(entry)->Ranges) {
auto device = range->Device();
auto & statuses = devicesRangesStatuses[device];
if (device->GetIsDisconnected()) {
// limited polling mode
if (statuses.empty()) {
// First interaction with disconnected device within this cycle: Try to reconnect
if (device->HasSetupItems()) {
auto wrote = device->WriteSetupRegisters(false);
statuses.insert(wrote ? TRegisterRange::ST_OK : TRegisterRange::ST_UNKNOWN_ERROR);
if (!wrote) {
continue;
}
}
} else {
// Not first interaction with disconnected device that has only errors - still disconnected
if (statuses.count(TRegisterRange::ST_UNKNOWN_ERROR) == statuses.size()) {
continue;
}
}
}
PollRange(range);
statuses.insert(range->GetStatus());
if (range->NeedsSplit()) {
rangesToSplit.insert(range);
}
}
MaybeFlushAvoidingPollStarvationButDontWait();
});
for (const auto & deviceRangesStatuses: devicesRangesStatuses) {
const auto & device = deviceRangesStatuses.first;
const auto & statuses = deviceRangesStatuses.second;
if (statuses.empty()) {
std::cerr << "invariant violation: statuses empty @ " << __func__ << std::endl;
continue; // this should not happen
}
bool deviceWasDisconnected = device->GetIsDisconnected(); // don't move after device->OnCycleEnd(...);
{
bool cycleFailed = statuses.count(TRegisterRange::ST_UNKNOWN_ERROR) == statuses.size();
device->OnCycleEnd(!cycleFailed);
}
if (deviceWasDisconnected && !device->GetIsDisconnected()) {
OnDeviceReconnect(device);
}
}
SplitRegisterRanges(std::move(rangesToSplit));
for (const auto& p: DevicesList) {
p->EndPollCycle();
}
// Port status
{
bool cycleFailed = std::all_of(DevicesList.begin(), DevicesList.end(),
[](const PSerialDevice & device){ return device->GetIsDisconnected(); }
);
Port->CycleEnd(!cycleFailed);
}
}
bool TSerialClient::WriteSetupRegisters(PSerialDevice dev)
{
Connect();
PrepareToAccessDevice(dev);
return dev->WriteSetupRegisters();
}
void TSerialClient::SetTextValue(PRegister reg, const std::string& value)
{
GetHandler(reg)->SetTextValue(value);
}
std::string TSerialClient::GetTextValue(PRegister reg) const
{
return GetHandler(reg)->TextValue();
}
bool TSerialClient::DidRead(PRegister reg) const
{
return GetHandler(reg)->DidRead();
}
void TSerialClient::SetReadCallback(const TSerialClient::TReadCallback& callback)
{
ReadCallback = callback;
}
void TSerialClient::SetErrorCallback(const TSerialClient::TErrorCallback& callback)
{
ErrorCallback = callback;
}
void TSerialClient::SetDebug(bool debug)
{
Debug = debug;
Port->SetDebug(debug);
for (const auto& p: Handlers)
p.second->SetDebug(debug);
}
bool TSerialClient::DebugEnabled() const {
return Debug;
}
void TSerialClient::NotifyFlushNeeded()
{
FlushNeeded->Signal();
}
PRegisterHandler TSerialClient::GetHandler(PRegister reg) const
{
auto it = Handlers.find(reg);
if (it == Handlers.end())
throw TSerialDeviceException("register not found");
return it->second;
}
void TSerialClient::PrepareToAccessDevice(PSerialDevice dev)
{
if (dev != LastAccessedDevice) {
LastAccessedDevice = dev;
dev->Prepare();
}
}
void TSerialClient::OnDeviceReconnect(PSerialDevice dev)
{
if (Debug) {
std::cerr << "device " << dev->ToString() << " reconnected" << std::endl;
}
dev->ResetUnavailableAddresses();
}