-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgpio.cpp
594 lines (531 loc) · 18.9 KB
/
gpio.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
// 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 "gpio.hpp"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#ifdef ESP_PLATFORM
#include "driver/gpio.h"
#else
#include <fcntl.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "gpio.h" // NS9XXX GPIO header, included in project
#endif
#include "logger.hpp"
#include "mainloop.hpp"
using namespace p44;
#ifdef ESP_PLATFORM
// MARK: - GPIO via ESP32 gpio
GpioPin::GpioPin(int aGpioNo, bool aOutput, bool aInitialState, Tristate aPull) :
gpioNo((gpio_num_t)aGpioNo),
output(aOutput),
pinState(aInitialState)
#ifndef ESP_PLATFORM
,gpioFD(-1)
#endif
{
esp_err_t ret;
// make sure pin is set to GPIO
ret = gpio_reset_pin(gpioNo);
if (ret==ESP_OK) {
// set pullup/down
ret = gpio_set_pull_mode(gpioNo, aPull==yes ? GPIO_PULLUP_ONLY : (aPull==no ? GPIO_PULLUP_PULLDOWN : GPIO_FLOATING));
}
if (ret==ESP_OK) {
// set direction
ret = gpio_set_direction(gpioNo, output ? GPIO_MODE_OUTPUT : GPIO_MODE_INPUT);
if (output && ret==ESP_OK) {
// set initial state
ret = gpio_set_level(gpioNo, pinState ? 1 : 0);
}
}
if (ret!=ESP_OK) {
LOG(LOG_ERR,"GPIO init error: %s", esp_err_to_name(ret));
gpio_reset_pin(gpioNo);
gpioNo = GPIO_NUM_NC; // signal "not connected"
}
}
GpioPin::~GpioPin()
{
// reset to default (disabled) state
gpio_reset_pin(gpioNo);
}
bool GpioPin::getState()
{
if (output) {
return pinState; // just return last set state
}
else {
// is input
if (gpioNo!=GPIO_NUM_NC) {
return gpio_get_level(gpioNo);
}
}
return false; // non-working pins always return false
}
bool GpioPin::setInputChangedHandler(InputChangedCB aInputChangedCB, bool aInverted, bool aInitialState, MLMicroSeconds aDebounceTime, MLMicroSeconds aPollInterval)
{
// TODO: implement interrupts
// for now use poll-based input change detection
return inherited::setInputChangedHandler(aInputChangedCB, aInverted, aInitialState, aDebounceTime, aPollInterval);
/*
if (aInputChangedCB==NULL) {
// release handler
MainLoop::currentMainLoop().unregisterPollHandler(gpioFD);
return inherited::setInputChangedHandler(aInputChangedCB, aInverted, aInitialState, aDebounceTime, aPollInterval);
}
// anyway, save parameters for base class
inputChangedCB = aInputChangedCB;
invertedReporting = aInverted;
currentState = aInitialState;
debounceTime = aDebounceTime;
// try to open "edge" to configure interrupt
string edgePath = string_format("%s/gpio%d/edge", GPIO_SYS_CLASS_PATH, gpioNo);
int edgeFd = open(edgePath.c_str(), O_RDWR);
if (edgeFd<0) {
LOG(LOG_DEBUG, "GPIO edge file does not exist -> GPIO %d has no edge interrupt capability", gpioNo);
// use poll-based input change detection
return inherited::setInputChangedHandler(aInputChangedCB, aInverted, aInitialState, aDebounceTime, aPollInterval);
}
// enable triggering on both edges
string s = "both";
ssize_t ret = write(edgeFd, s.c_str(), s.length());
if (ret<0) { LOG(LOG_ERR, "Cannot write to GPIO edge file %s", strerror(errno)); return false; }
close(edgeFd);
// establish a IO poll
MainLoop::currentMainLoop().registerPollHandler(gpioFD, POLLPRI, boost::bind(&GpioPin::stateChanged, this, _2));
return true;
*/
}
bool GpioPin::stateChanged(int aPollFlags)
{
bool newState = getState();
//LOG(LOG_DEBUG, "GPIO %d edge detected (poll() returned POLLPRI for value file) : new state = %d", gpioNo, newState);
inputHasChangedTo(newState);
return true; // handled
}
void GpioPin::setState(bool aState)
{
if (!output) return; // non-outputs cannot be set
if (gpioNo==GPIO_NUM_NC) return; // non-existing pins cannot be set
pinState = aState;
// - set value
gpio_set_level(gpioNo, pinState ? 1 : 0);
}
#else
// MARK: - LEDs via modern kernel support
#define GPIO_LED_CLASS_PATH "/sys/class/leds"
GpioLedPin::GpioLedPin(const char* aLedName, bool aInitialState) :
ledState(aInitialState),
ledFD(-1)
{
string name;
if (isdigit(*aLedName)) {
// old style number-only -> prefix with "led"
name = string_format("%s/led%s/brightness", GPIO_LED_CLASS_PATH, aLedName);
}
else {
// modern alphanumeric LED name -> use as-is
name = string_format("%s/%s/brightness", GPIO_LED_CLASS_PATH, aLedName);
}
ledFD = open(name.c_str(), O_RDWR);
if (ledFD<0) { LOG(LOG_ERR, "Cannot open LED brightness file %s: %s", name.c_str(), strerror(errno)); return; }
// set initial state
setState(ledState);
}
GpioLedPin::~GpioLedPin()
{
if (ledFD>0) {
close(ledFD);
}
}
bool GpioLedPin::getState()
{
return ledState; // just return last set state
}
void GpioLedPin::setState(bool aState)
{
if (ledFD<0) return; // non-existing pins cannot be set
ledState = aState;
// - set value
char buf[2];
buf[0] = ledState ? '1' : '0';
buf[1] = 0;
write(ledFD, buf, 1);
}
// MARK: - GPIO via modern kernel support
#define GPIO_SYS_CLASS_PATH "/sys/class/gpio"
GpioPin::GpioPin(int aGpioNo, bool aOutput, bool aInitialState, Tristate aPull) :
gpioNo(aGpioNo),
output(aOutput),
pinState(aInitialState),
gpioFD(-1)
{
// TODO: convert to modern character device based gpio, implement pull up/down.
int tempFd;
ssize_t ret;
string name;
string s = string_format("%d", gpioNo);
// have the kernel export the pin
name = string_format("%s/export",GPIO_SYS_CLASS_PATH);
tempFd = open(name.c_str(), O_WRONLY);
if (tempFd<0) { LOG(LOG_ERR, "Cannot open GPIO export file %s: %s", name.c_str(), strerror(errno)); return; }
ret = write(tempFd, s.c_str(), s.length());
if (ret<0) { LOG(LOG_WARNING, "Cannot write '%s' to GPIO export file %s: %s, probably already exported", s.c_str(), name.c_str(), strerror(errno)); }
close(tempFd);
// save base path
string basePath = string_format("%s/gpio%d", GPIO_SYS_CLASS_PATH, gpioNo);
// configure
name = basePath + "/direction";
tempFd = open(name.c_str(), O_RDWR);
if (tempFd<0) { LOG(LOG_ERR, "Cannot open GPIO direction file %s: %s", name.c_str(), strerror(errno)); return; }
if (output) {
// output
// - set output with initial value
s = pinState ? "high" : "low";
ret = write(tempFd, s.c_str(), s.length());
}
else {
// input
// - set input
s = "in";
ret = write(tempFd, s.c_str(), s.length());
}
if (ret<0) { LOG(LOG_WARNING, "Cannot write '%s' to GPIO direction file %s: %s", s.c_str(), name.c_str(), strerror(errno)); }
close(tempFd);
// now keep the value FD open
name = basePath + "/value";
gpioFD = open(name.c_str(), O_RDWR);
if (gpioFD<0) { LOG(LOG_ERR, "Cannot open GPIO value file %s: %s", name.c_str(), strerror(errno)); return; }
}
GpioPin::~GpioPin()
{
if (gpioFD>0) {
MainLoop::currentMainLoop().unregisterPollHandler(gpioFD);
close(gpioFD);
}
}
bool GpioPin::getState()
{
if (output)
return pinState; // just return last set state
else {
// is input
if (gpioFD<0)
return false; // non-working pins always return false
else {
// read from input
char buf[2];
lseek(gpioFD, 0, SEEK_SET);
if (read(gpioFD, buf, 1)>0) {
return buf[0]!='0';
}
}
}
return false;
}
bool GpioPin::setInputChangedHandler(InputChangedCB aInputChangedCB, bool aInverted, bool aInitialState, MLMicroSeconds aDebounceTime, MLMicroSeconds aPollInterval)
{
if (aInputChangedCB==NULL) {
// release handler
MainLoop::currentMainLoop().unregisterPollHandler(gpioFD);
return inherited::setInputChangedHandler(aInputChangedCB, aInverted, aInitialState, aDebounceTime, aPollInterval);
}
// anyway, save parameters for base class
inputChangedCB = aInputChangedCB;
invertedReporting = aInverted;
currentState = aInitialState;
debounceTime = aDebounceTime;
// try to open "edge" to configure interrupt
string edgePath = string_format("%s/gpio%d/edge", GPIO_SYS_CLASS_PATH, gpioNo);
int edgeFd = open(edgePath.c_str(), O_RDWR);
if (edgeFd<0) {
LOG(LOG_DEBUG, "GPIO edge file does not exist -> GPIO %d has no edge interrupt capability", gpioNo);
// use poll-based input change detection
return inherited::setInputChangedHandler(aInputChangedCB, aInverted, aInitialState, aDebounceTime, aPollInterval);
}
// enable triggering on both edges
string s = "both";
ssize_t ret = write(edgeFd, s.c_str(), s.length());
if (ret<0) { LOG(LOG_ERR, "Cannot write to GPIO edge file %s", strerror(errno)); return false; }
close(edgeFd);
// establish a IO poll
MainLoop::currentMainLoop().registerPollHandler(gpioFD, POLLPRI, boost::bind(&GpioPin::stateChanged, this, _2));
return true;
}
bool GpioPin::stateChanged(int aPollFlags)
{
bool newState = getState();
//LOG(LOG_DEBUG, "GPIO %d edge detected (poll() returned POLLPRI for value file) : new state = %d", gpioNo, newState);
inputHasChangedTo(newState);
return true; // handled
}
void GpioPin::setState(bool aState)
{
if (!output) return; // non-outputs cannot be set
if (gpioFD<0) return; // non-existing pins cannot be set
pinState = aState;
// - set value
char buf[2];
buf[0] = pinState ? '1' : '0';
buf[1] = 0;
write(gpioFD, buf, 1);
}
// Sysfs Interface for Userspace (OPTIONAL)
// ========================================
// Platforms which use the "gpiolib" implementors framework may choose to
// configure a sysfs user interface to GPIOs. This is different from the
// debugfs interface, since it provides control over GPIO direction and
// value instead of just showing a gpio state summary. Plus, it could be
// present on production systems without debugging support.
//
// Given appropriate hardware documentation for the system, userspace could
// know for example that GPIO #23 controls the write protect line used to
// protect boot loader segments in flash memory. System upgrade procedures
// may need to temporarily remove that protection, first importing a GPIO,
// then changing its output state, then updating the code before re-enabling
// the write protection. In normal use, GPIO #23 would never be touched,
// and the kernel would have no need to know about it.
//
// Again depending on appropriate hardware documentation, on some systems
// userspace GPIO can be used to determine system configuration data that
// standard kernels won't know about. And for some tasks, simple userspace
// GPIO drivers could be all that the system really needs.
//
// Note that standard kernel drivers exist for common "LEDs and Buttons"
// GPIO tasks: "leds-gpio" and "gpio_keys", respectively. Use those
// instead of talking directly to the GPIOs; they integrate with kernel
// frameworks better than your userspace code could.
//
//
// Paths in Sysfs
// --------------
// There are three kinds of entry in /sys/class/gpio:
//
// - Control interfaces used to get userspace control over GPIOs;
//
// - GPIOs themselves; and
//
// - GPIO controllers ("gpio_chip" instances).
//
// That's in addition to standard files including the "device" symlink.
//
// The control interfaces are write-only:
//
// /sys/class/gpio/
//
// "export" ... Userspace may ask the kernel to export control of
// a GPIO to userspace by writing its number to this file.
//
// Example: "echo 19 > export" will create a "gpio19" node
// for GPIO #19, if that's not requested by kernel code.
//
// "unexport" ... Reverses the effect of exporting to userspace.
//
// Example: "echo 19 > unexport" will remove a "gpio19"
// node exported using the "export" file.
//
// GPIO signals have paths like /sys/class/gpio/gpio42/ (for GPIO #42)
// and have the following read/write attributes:
//
// /sys/class/gpio/gpioN/
//
// "direction" ... reads as either "in" or "out". This value may
// normally be written. Writing as "out" defaults to
// initializing the value as low. To ensure glitch free
// operation, values "low" and "high" may be written to
// configure the GPIO as an output with that initial value.
//
// Note that this attribute *will not exist* if the kernel
// doesn't support changing the direction of a GPIO, or
// it was exported by kernel code that didn't explicitly
// allow userspace to reconfigure this GPIO's direction.
//
// "value" ... reads as either 0 (low) or 1 (high). If the GPIO
// is configured as an output, this value may be written;
// any nonzero value is treated as high.
//
// If the pin can be configured as interrupt-generating interrupt
// and if it has been configured to generate interrupts (see the
// description of "edge"), you can poll(2) on that file and
// poll(2) will return whenever the interrupt was triggered. If
// you use poll(2), set the events POLLPRI and POLLERR. If you
// use select(2), set the file descriptor in exceptfds. After
// poll(2) returns, either lseek(2) to the beginning of the sysfs
// file and read the new value or close the file and re-open it
// to read the value.
//
// "edge" ... reads as either "none", "rising", "falling", or
// "both". Write these strings to select the signal edge(s)
// that will make poll(2) on the "value" file return.
//
// This file exists only if the pin can be configured as an
// interrupt generating input pin.
//
// "active_low" ... reads as either 0 (false) or 1 (true). Write
// any nonzero value to invert the value attribute both
// for reading and writing. Existing and subsequent
// poll(2) support configuration via the edge attribute
// for "rising" and "falling" edges will follow this
// setting.
//
// GPIO controllers have paths like /sys/class/gpio/gpiochip42/ (for the
// controller implementing GPIOs starting at #42) and have the following
// read-only attributes:
//
// /sys/class/gpio/gpiochipN/
//
// "base" ... same as N, the first GPIO managed by this chip
//
// "label" ... provided for diagnostics (not always unique)
//
// "ngpio" ... how many GPIOs this manges (N to N + ngpio - 1)
//
// Board documentation should in most cases cover what GPIOs are used for
// what purposes. However, those numbers are not always stable; GPIOs on
// a daughtercard might be different depending on the base board being used,
// or other cards in the stack. In such cases, you may need to use the
// gpiochip nodes (possibly in conjunction with schematics) to determine
// the correct GPIO number to use for a given signal.
//
//
// Exporting from Kernel code
// --------------------------
// Kernel code can explicitly manage exports of GPIOs which have already been
// requested using gpio_request():
//
// /* export the GPIO to userspace */
// int gpio_export(unsigned gpio, bool direction_may_change);
//
// /* reverse gpio_export() */
// void gpio_unexport();
//
// /* create a sysfs link to an exported GPIO node */
// int gpio_export_link(struct device *dev, const char *name,
// unsigned gpio)
//
// /* change the polarity of a GPIO node in sysfs */
// int gpio_sysfs_set_active_low(unsigned gpio, int value);
//
// After a kernel driver requests a GPIO, it may only be made available in
// the sysfs interface by gpio_export(). The driver can control whether the
// signal direction may change. This helps drivers prevent userspace code
// from accidentally clobbering important system state.
//
// This explicit exporting can help with debugging (by making some kinds
// of experiments easier), or can provide an always-there interface that's
// suitable for documenting as part of a board support package.
//
// After the GPIO has been exported, gpio_export_link() allows creating
// symlinks from elsewhere in sysfs to the GPIO sysfs node. Drivers can
// use this to provide the interface under their own device in sysfs with
// a descriptive name.
//
// Drivers can use gpio_sysfs_set_active_low() to hide GPIO line polarity
// differences between boards from user space. This only affects the
// sysfs interface. Polarity change can be done both before and after
// gpio_export(), and previously enabled poll(2) support for either
// rising or falling edge will be reconfigured to follow this setting.
// MARK: - GPIO for NS9xxx (Digi ME 9210 LX)
GpioNS9XXXPin::GpioNS9XXXPin(const char* aGpioName, bool aOutput, bool aInitialState) :
gpioFD(-1),
pinState(false)
{
// save params
output = aOutput;
name = aGpioName;
pinState = aInitialState; // set even for inputs
int ret_val;
// open device
string gpiopath(GPION9XXX_DEVICES_BASEPATH);
gpiopath.append(name);
gpioFD = open(gpiopath.c_str(), O_RDWR);
if (gpioFD<0) {
LOG(LOG_ERR, "Cannot open GPIO device %s: %s", name.c_str(), strerror(errno));
return;
}
// configure
if (output) {
// output
if ((ret_val = ioctl(gpioFD, GPIO_CONFIG_AS_OUT)) < 0) {
LOG(LOG_ERR, "GPIO_CONFIG_AS_OUT failed for %s: %s", name.c_str(), strerror(errno));
return;
}
// set state immediately
setState(pinState);
}
else {
// input
if ((ret_val = ioctl(gpioFD, GPIO_CONFIG_AS_INP)) < 0) {
LOG(LOG_ERR, "GPIO_CONFIG_AS_INP failed for %s: %s", name.c_str(), strerror(errno));
return;
}
}
}
GpioNS9XXXPin::~GpioNS9XXXPin()
{
if (gpioFD>0) {
close(gpioFD);
}
}
bool GpioNS9XXXPin::getState()
{
if (output)
return pinState; // just return last set state
if (gpioFD<0)
return false; // non-working pins always return false
else {
// read from input
int inval;
#ifndef __APPLE__
int ret_val;
if ((ret_val = ioctl(gpioFD, GPIO_READ_PIN_VAL, &inval)) < 0) {
LOG(LOG_ERR, "GPIO_READ_PIN_VAL failed for %s: %s", name.c_str(), strerror(errno));
return false;
}
#else
DBGLOG(LOG_ERR, "ioctl(gpioFD, GPIO_READ_PIN_VAL, &dummy)");
inval = 0;
#endif
return (bool)inval;
}
}
void GpioNS9XXXPin::setState(bool aState)
{
if (!output) return; // non-outputs cannot be set
if (gpioFD<0) return; // non-existing pins cannot be set
pinState = aState;
// - set value
int setval = pinState;
#ifndef __APPLE__
int ret_val;
if ((ret_val = ioctl(gpioFD, GPIO_WRITE_PIN_VAL, &setval)) < 0) {
LOG(LOG_ERR, "GPIO_WRITE_PIN_VAL failed for %s: %s", name.c_str(), strerror(errno));
return;
}
#else
DBGLOG(LOG_ERR, "ioctl(gpioFD, GPIO_WRITE_PIN_VAL, %d)", setval);
#endif
}
#endif // !ESP_PLATFORM