-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathiopin.cpp
433 lines (360 loc) · 10.7 KB
/
iopin.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Copyright (c) 2013-2023 plan44.ch / Lukas Zeller, Zurich, Switzerland
//
// Author: Lukas Zeller <luz@plan44.ch>
//
// This file is part of p44utils.
//
// p44utils is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// p44utils is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with p44utils. If not, see <http://www.gnu.org/licenses/>.
//
#include "iopin.hpp"
using namespace p44;
// MARK: - IOPin
IOPin::IOPin() :
currentState(false),
invertedReporting(false),
pollInterval(Never),
lastReportedChange(Never)
{
}
IOPin::~IOPin()
{
clearChangeHandling();
}
void IOPin::clearChangeHandling()
{
inputChangedCB = NoOP;
pollInterval = Never;
pollTicket.cancel();
debounceTicket.cancel();
}
#define IOPIN_DEFAULT_POLL_INTERVAL (25*MilliSecond)
bool IOPin::setInputChangedHandler(InputChangedCB aInputChangedCB, bool aInverted, bool aInitialState, MLMicroSeconds aDebounceTime, MLMicroSeconds aPollInterval)
{
inputChangedCB = aInputChangedCB;
pollInterval = aPollInterval;
currentState = aInitialState;
invertedReporting = aInverted;
debounceTime = aDebounceTime;
if (aInputChangedCB==NULL) {
// disable polling
clearChangeHandling();
}
else {
if (pollInterval<0)
return false; // cannot install non-polling input change handler
// install handler
if (pollInterval==0) {
// use default interval
pollInterval = IOPIN_DEFAULT_POLL_INTERVAL;
}
// schedule first poll
pollTicket.executeOnce(boost::bind(&IOPin::timedpoll, this, _1));
}
return true; // successful
}
void IOPin::inputHasChangedTo(bool aNewState)
{
if (aNewState!=currentState) {
debounceTicket.cancel();
MLMicroSeconds now = MainLoop::now();
// optional debouncing
if (debounceTime>0 && lastReportedChange!=Never) {
// check for debounce time passed
if (lastReportedChange+debounceTime>now) {
LOG(LOG_DEBUG, "- debouncing holdoff, will resample after debouncing time");
// debounce time not yet over, schedule an extra re-sample later and suppress reporting for now
debounceTicket.executeOnce(boost::bind(&IOPin::debounceSample, this), debounceTime);
return;
}
}
// report change now
LOG(LOG_DEBUG, "- state changed >=debouncing time after last change: new state = %d", aNewState);
currentState = aNewState;
lastReportedChange = now;
if (inputChangedCB) inputChangedCB(currentState!=invertedReporting);
}
}
void IOPin::debounceSample()
{
bool newState = getState();
LOG(LOG_DEBUG, "- debouncing time over, resampled state = %d", newState);
if (newState!=currentState) {
currentState = newState;
lastReportedChange = MainLoop::now();
if (inputChangedCB) inputChangedCB(currentState!=invertedReporting);
}
}
void IOPin::timedpoll(MLTimer &aTimer)
{
inputHasChangedTo(getState());
// schedule next poll
MainLoop::currentMainLoop().retriggerTimer(aTimer, pollInterval, pollInterval/2); // allow 50% jitter
}
// MARK: - digital I/O simulation
static char nextIoSimKey = 'a';
SimPin::SimPin(const char *aName, bool aOutput, bool aInitialState) :
name(aName),
output(aOutput),
pinState(aInitialState)
{
LOG(LOG_ALERT, "Initialized SimPin \"%s\" as %s with initial state %s", name.c_str(), aOutput ? "output" : "input", pinState ? "HI" : "LO");
#if !DISABLE_CONSOLEKEY
size_t n = name.find(":");
char key = 0;
if (n!=string::npos && name.size()>n+1) {
key = name[n+1];
}
else {
key = nextIoSimKey++;
}
if (!aOutput) {
if (!output) {
consoleKey = ConsoleKeyManager::sharedKeyManager()->newConsoleKey(
key,
name.c_str(),
pinState
);
}
}
#endif
}
bool SimPin::getState()
{
if (output) {
return pinState; // just return last set state
}
else {
#if DISABLE_CONSOLEKEY
return false; // no input at all
#else
return (bool)consoleKey->isSet();
#endif
}
}
void SimPin::setState(bool aState)
{
if (!output) return; // non-outputs cannot be set
if (pinState!=aState) {
pinState = aState;
LOG(LOG_ALERT, ">>> SimPin \"%s\" set to %s", name.c_str(), pinState ? "HI" : "LO");
}
}
// MARK: - digital output via system command
#if !DISABLE_SYSTEMCMDIO && !defined(ESP_PLATFORM)
SysCommandPin::SysCommandPin(const char *aConfig, bool aOutput, bool aInitialState) :
pinState(aInitialState),
output(aOutput),
changePending(false),
changing(false)
{
// separate commands for switching on and off
// oncommand|offcommand
string s = aConfig;
size_t i = s.find("|", 0);
if (i!=string::npos) {
onCommand = s.substr(0,i);
offCommand = s.substr(i+1);
}
// force setting initial state
pinState = !aInitialState;
setState(aInitialState);
}
string SysCommandPin::stateSetCommand(bool aState)
{
return aState ? onCommand : offCommand;
}
void SysCommandPin::setState(bool aState)
{
if (!output) return; // non-outputs cannot be set
if (pinState!=aState) {
pinState = aState;
// schedule change
applyState(aState);
}
}
void SysCommandPin::applyState(bool aState)
{
if (changing) {
// already in process of applying a change
changePending = true;
}
else {
// trigger change
changing = true;
MainLoop::currentMainLoop().fork_and_system(boost::bind(&SysCommandPin::stateUpdated, this, _1, _2), stateSetCommand(aState).c_str());
}
}
void SysCommandPin::stateUpdated(ErrorPtr aError, const string &aOutputString)
{
if (Error::notOK(aError)) {
LOG(LOG_WARNING, "SysCommandPin set state=%d: command (%s) execution failed: %s", pinState, stateSetCommand(pinState).c_str(), aError->text());
}
else {
LOG(LOG_INFO, "SysCommandPin set state=%d: command (%s) executed successfully", pinState, stateSetCommand(pinState).c_str());
}
changing = false;
if (changePending) {
changePending = false;
// apply latest value
applyState(pinState);
}
}
#endif // !DISABLE_SYSTEMCMDIO && !defined(ESP_PLATFORM)
// MARK: - analog I/O simulation
AnalogSimPin::AnalogSimPin(const char *aName, bool aOutput, double aInitialValue) :
name(aName),
output(aOutput),
pinValue(aInitialValue)
{
LOG(LOG_ALERT, "Initialized AnalogSimPin \"%s\" as %s with initial value %.2f", name.c_str(), aOutput ? "output" : "input", pinValue);
#if !DISABLE_CONSOLEKEY
if (!aOutput) {
if (!output) {
consoleKeyUp = ConsoleKeyManager::sharedKeyManager()->newConsoleKey(
nextIoSimKey++,
"increase",
false
);
consoleKeyUp->setConsoleKeyHandler(boost::bind(&AnalogSimPin::simKeyPress, this, 1, _1));
consoleKeyDown = ConsoleKeyManager::sharedKeyManager()->newConsoleKey(
nextIoSimKey++,
"decrease",
false
);
consoleKeyDown->setConsoleKeyHandler(boost::bind(&AnalogSimPin::simKeyPress, this, -1, _1));
}
}
#endif
}
#if !DISABLE_CONSOLEKEY
void AnalogSimPin::simKeyPress(int aDir, bool aNewState)
{
if (aNewState) {
pinValue += 0.1*aDir;
LOG(LOG_ALERT, ">>> AnalogSimPin \"%s\" manually changed to %.2f", name.c_str(), pinValue);
}
}
#endif
double AnalogSimPin::getValue()
{
return pinValue; // just return last set value (as set by setValue or modified by key presses)
}
void AnalogSimPin::setValue(double aValue)
{
if (!output) return; // non-outputs cannot be set
if (pinValue!=aValue) {
pinValue = aValue;
LOG(LOG_ALERT, ">>> AnalogSimPin \"%s\" set to %.2f", name.c_str(), pinValue);
}
}
// MARK: - analog output via system command
#if !DISABLE_SYSTEMCMDIO && !defined(ESP_PLATFORM)
AnalogSysCommandPin::AnalogSysCommandPin(const char *aConfig, bool aOutput, double aInitialValue) :
pinValue(aInitialValue),
output(aOutput),
range(100),
changePending(false),
changing(false)
{
// Save set command
// [range|]offcommand
setCommand = aConfig;
size_t i = setCommand.find("|", 0);
// check for range
if (i!=string::npos) {
sscanf(setCommand.substr(0,i).c_str(), "%d", &range);
setCommand.erase(0,i+1);
}
// force setting initial state
pinValue = aInitialValue+1;
setValue(aInitialValue);
}
string AnalogSysCommandPin::valueSetCommand(double aValue)
{
size_t vpos = setCommand.find("${VALUE}");
string cmd;
if (vpos!=string::npos) {
cmd = setCommand;
cmd.replace(vpos, vpos+8, string_format("%d", (int)(aValue/100*range))); // aValue assumed to be 0..100
}
return cmd;
}
void AnalogSysCommandPin::setValue(double aValue)
{
if (!output) return; // non-outputs cannot be set
if (aValue!=pinValue) {
pinValue = aValue;
// schedule change
applyValue(aValue);
}
}
void AnalogSysCommandPin::applyValue(double aValue)
{
if (changing) {
// already in process of applying a change
changePending = true;
}
else {
// trigger change
changing = true;
MainLoop::currentMainLoop().fork_and_system(boost::bind(&AnalogSysCommandPin::valueUpdated, this, _1, _2), valueSetCommand(aValue).c_str());
}
}
void AnalogSysCommandPin::valueUpdated(ErrorPtr aError, const string &aOutputString)
{
if (Error::notOK(aError)) {
LOG(LOG_WARNING, "AnalogSysCommandPin set value=%.2f: command (%s) execution failed: %s", pinValue, valueSetCommand(pinValue).c_str(), aError->text());
}
else {
LOG(LOG_INFO, "AnalogSysCommandPin set value=%.2f: command (%s) executed successfully", pinValue, valueSetCommand(pinValue).c_str());
}
changing = false;
if (changePending) {
changePending = false;
// apply latest value
applyValue(pinValue);
}
}
#endif // !DISABLE_SYSTEMCMDIO && !defined(ESP_PLATFORM)
// MARK: - analog I/O simulation from fd
AnalogSimPinFd::AnalogSimPinFd(const char *aName, bool aOutput, double aInitialValue) :
name(aName),
output(aOutput),
pinValue(aInitialValue)
{
LOG(LOG_ALERT, "Initialized AnalogSimPinFd \"%s\" as %s with initial value %.2f", name.c_str(), aOutput ? "output" : "input", pinValue);
fd = open(aName, O_RDWR);
}
double AnalogSimPinFd::getValue()
{
char buf[20];
lseek(fd, 0, SEEK_SET);
if (read(fd, buf, 20) > 0) {
pinValue = atof(buf);
}
return pinValue;
}
void AnalogSimPinFd::setValue(double aValue)
{
if (!output) return; // non-outputs cannot be set
if (pinValue!=aValue) {
pinValue = aValue;
char buf[20];
snprintf(buf, 20, "%f\n", pinValue);
lseek(fd, 0, SEEK_SET);
write(fd, buf, strlen(buf));
}
}