SysFsDriver.cs 30.4 KB
Newer Older
1 2 3 4 5
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
6
using System.Diagnostics;
7
using System.Globalization;
8 9 10 11 12 13 14 15 16
using System.IO;
using System.Linq;
using System.Threading;

namespace System.Device.Gpio.Drivers
{
    /// <summary>
    /// A GPIO driver for Unix.
    /// </summary>
G
Greg Ingram 已提交
17
    public class SysFsDriver : UnixDriver
18 19
    {
        private const string GpioBasePath = "/sys/class/gpio";
20 21 22 23
        private const string GpioChip = "gpiochip";
        private const string GpioLabel = "/label";
        private const string GpioContoller = "pinctrl";
        private const string GpioOffsetBase = "/base";
P
Patrick Grawehr 已提交
24
        private const int PollingTimeout = 50;
25
        private readonly CancellationTokenSource _eventThreadCancellationTokenSource;
26 27
        private readonly List<int> _exportedPins = new List<int>();
        private readonly Dictionary<int, UnixDriverDevicePin> _devicePins = new Dictionary<int, UnixDriverDevicePin>();
28
        private static readonly int s_pinOffset = ReadOffset();
P
Patrick Grawehr 已提交
29
        private TimeSpan _statusUpdateSleepTime = TimeSpan.FromMilliseconds(1);
30
        private int _pollFileDescriptor = -1;
31
        private Thread? _eventDetectionThread;
32
        private int _pinsToDetectEventsCount;
33 34 35 36 37 38 39 40 41 42 43 44 45

        private static int ReadOffset()
        {
            IEnumerable<string> fileNames = Directory.EnumerateFileSystemEntries(GpioBasePath);
            foreach (string name in fileNames)
            {
                if (name.Contains(GpioChip))
                {
                    try
                    {
                        if (File.ReadAllText($"{name}{GpioLabel}").StartsWith(GpioContoller, StringComparison.Ordinal))
                        {
                            if (int.TryParse(File.ReadAllText($"{name}{GpioOffsetBase}"), out int pinOffset))
46
                            {
47
                                return pinOffset;
48
                            }
49 50
                        }
                    }
51 52 53
                    catch (IOException)
                    {
                        // Ignoring file not found or any other IO exceptions as it is not guaranteed the folder would have files "label" "base"
54
                        // And don't want to throw in this case just continue to load the gpiochip with default offset = 0
55
                    }
56 57
                }
            }
58

59 60
            return 0;
        }
61

62 63 64
        /// <summary>
        /// Initializes a new instance of the <see cref="SysFsDriver"/> class.
        /// </summary>
65 66
        public SysFsDriver()
        {
67 68 69 70 71
            if (Environment.OSVersion.Platform != PlatformID.Unix)
            {
                throw new PlatformNotSupportedException($"{GetType().Name} is only supported on Linux/Unix.");
            }

72
            _eventThreadCancellationTokenSource = new CancellationTokenSource();
73 74
        }

P
Patrick Grawehr 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        /// <summary>
        /// The sleep time after an event occured and before the new value is read.
        /// </summary>
        internal TimeSpan StatusUpdateSleepTime
        {
            get
            {
                return _statusUpdateSleepTime;
            }
            set
            {
                _statusUpdateSleepTime = value;
            }
        }

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        /// <summary>
        /// The number of pins provided by the driver.
        /// </summary>
        protected internal override int PinCount => throw new PlatformNotSupportedException("This driver is generic so it can not enumerate how many pins are available.");

        /// <summary>
        /// Converts a board pin number to the driver's logical numbering scheme.
        /// </summary>
        /// <param name="pinNumber">The board pin number to convert.</param>
        /// <returns>The pin number in the driver's logical numbering scheme.</returns>
        protected internal override int ConvertPinNumberToLogicalNumberingScheme(int pinNumber) => throw new PlatformNotSupportedException("This driver is generic so it can not perform conversions between pin numbering schemes.");

        /// <summary>
        /// Opens a pin in order for it to be ready to use.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
        protected internal override void OpenPin(int pinNumber)
        {
108 109
            int pinOffset = pinNumber + s_pinOffset;
            string pinPath = $"{GpioBasePath}/gpio{pinOffset}";
110 111 112 113 114
            // If the directory exists, this becomes a no-op since the pin might have been opened already by the some controller or somebody else.
            if (!Directory.Exists(pinPath))
            {
                try
                {
115
                    File.WriteAllText(Path.Combine(GpioBasePath, "export"), pinOffset.ToString(CultureInfo.InvariantCulture));
K
Krzysztof Wicher 已提交
116
                    SysFsHelpers.EnsureReadWriteAccessToPath(pinPath);
117

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
                    _exportedPins.Add(pinNumber);
                }
                catch (UnauthorizedAccessException e)
                {
                    // Wrapping the exception in order to get a better message.
                    throw new UnauthorizedAccessException("Opening pins requires root permissions.", e);
                }
            }
        }

        /// <summary>
        /// Closes an open pin.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
        protected internal override void ClosePin(int pinNumber)
        {
134 135
            int pinOffset = pinNumber + s_pinOffset;
            string pinPath = $"{GpioBasePath}/gpio{pinOffset}";
136 137 138 139 140 141
            // If the directory doesn't exist, this becomes a no-op since the pin was closed already.
            if (Directory.Exists(pinPath))
            {
                try
                {
                    SetPinEventsToDetect(pinNumber, PinEventTypes.None);
P
Patrick Grawehr 已提交
142 143 144 145 146 147
                    if (_devicePins.ContainsKey(pinNumber))
                    {
                        _devicePins[pinNumber].Dispose();
                        _devicePins.Remove(pinNumber);
                    }

148
                    File.WriteAllText(Path.Combine(GpioBasePath, "unexport"), pinOffset.ToString(CultureInfo.InvariantCulture));
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
                    _exportedPins.Remove(pinNumber);
                }
                catch (UnauthorizedAccessException e)
                {
                    throw new UnauthorizedAccessException("Closing pins requires root permissions.", e);
                }
            }
        }

        /// <summary>
        /// Sets the mode to a pin.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
        /// <param name="mode">The mode to be set.</param>
        protected internal override void SetPinMode(int pinNumber, PinMode mode)
        {
            if (mode == PinMode.InputPullDown || mode == PinMode.InputPullUp)
            {
                throw new PlatformNotSupportedException("This driver is generic so it does not support Input Pull Down or Input Pull Up modes.");
            }
169

170
            string directionPath = $"{GpioBasePath}/gpio{pinNumber + s_pinOffset}/direction";
G
Greg Ingram 已提交
171
            string sysFsMode = ConvertPinModeToSysFsMode(mode);
172 173 174 175
            if (File.Exists(directionPath))
            {
                try
                {
G
Greg Ingram 已提交
176
                    File.WriteAllText(directionPath, sysFsMode);
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
                }
                catch (UnauthorizedAccessException e)
                {
                    throw new UnauthorizedAccessException("Setting a mode to a pin requires root permissions.", e);
                }
            }
            else
            {
                throw new InvalidOperationException("There was an attempt to set a mode to a pin that is not open.");
            }
        }

        private string ConvertPinModeToSysFsMode(PinMode mode)
        {
            if (mode == PinMode.Input)
            {
                return "in";
            }
195

196 197 198 199
            if (mode == PinMode.Output)
            {
                return "out";
            }
200

201 202 203
            throw new PlatformNotSupportedException($"{mode} is not supported by this driver.");
        }

G
Greg Ingram 已提交
204
        private PinMode ConvertSysFsModeToPinMode(string sysFsMode)
205
        {
G
Greg Ingram 已提交
206 207
            sysFsMode = sysFsMode.Trim();
            if (sysFsMode == "in")
208 209 210
            {
                return PinMode.Input;
            }
211

G
Greg Ingram 已提交
212
            if (sysFsMode == "out")
213 214 215
            {
                return PinMode.Output;
            }
216

G
Greg Ingram 已提交
217
            throw new ArgumentException($"Unable to parse {sysFsMode} as a PinMode.");
218 219 220 221 222 223 224 225 226 227
        }

        /// <summary>
        /// Reads the current value of a pin.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
        /// <returns>The value of the pin.</returns>
        protected internal override PinValue Read(int pinNumber)
        {
            PinValue result = default;
228
            string valuePath = $"{GpioBasePath}/gpio{pinNumber + s_pinOffset}/value";
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
            if (File.Exists(valuePath))
            {
                try
                {
                    string valueContents = File.ReadAllText(valuePath);
                    result = ConvertSysFsValueToPinValue(valueContents);
                }
                catch (UnauthorizedAccessException e)
                {
                    throw new UnauthorizedAccessException("Reading a pin value requires root permissions.", e);
                }
            }
            else
            {
                throw new InvalidOperationException("There was an attempt to read from a pin that is not open.");
            }
245

246 247 248 249 250
            return result;
        }

        private PinValue ConvertSysFsValueToPinValue(string value)
        {
251
            return value.Trim() switch
252
            {
253 254 255 256
                "0" => PinValue.Low,
                "1" => PinValue.High,
                _ => throw new ArgumentException($"Invalid GPIO pin value {value}.")
            };
257 258 259 260 261 262 263 264 265
        }

        /// <summary>
        /// Writes a value to a pin.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
        /// <param name="value">The value to be written to the pin.</param>
        protected internal override void Write(int pinNumber, PinValue value)
        {
266
            string valuePath = $"{GpioBasePath}/gpio{pinNumber + s_pinOffset}/value";
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
            if (File.Exists(valuePath))
            {
                try
                {
                    string sysFsValue = ConvertPinValueToSysFs(value);
                    File.WriteAllText(valuePath, sysFsValue);
                }
                catch (UnauthorizedAccessException e)
                {
                    throw new UnauthorizedAccessException("Reading a pin value requires root permissions.", e);
                }
            }
            else
            {
                throw new InvalidOperationException("There was an attempt to write to a pin that is not open.");
            }
        }

        private string ConvertPinValueToSysFs(PinValue value)
            => value == PinValue.High ? "1" : "0";

        /// <summary>
        /// Checks if a pin supports a specific mode.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
        /// <param name="mode">The mode to check.</param>
        /// <returns>The status if the pin supports the mode.</returns>
        protected internal override bool IsPinModeSupported(int pinNumber, PinMode mode)
        {
            // Unix driver does not support pull up or pull down resistors.
            if (mode == PinMode.InputPullDown || mode == PinMode.InputPullUp)
            {
                return false;
            }
301

302 303 304 305 306 307 308
            return true;
        }

        /// <summary>
        /// Blocks execution until an event of type eventType is received or a cancellation is requested.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
P
Patrick Grawehr 已提交
309
        /// <param name="eventTypes">The event types to wait for. Can be <see cref="PinEventTypes.Rising"/>, <see cref="PinEventTypes.Falling"/> or both.</param>
310 311 312 313 314 315 316 317 318 319
        /// <param name="cancellationToken">The cancellation token of when the operation should stop waiting for an event.</param>
        /// <returns>A structure that contains the result of the waiting operation.</returns>
        protected internal override WaitForEventResult WaitForEvent(int pinNumber, PinEventTypes eventTypes, CancellationToken cancellationToken)
        {
            int pollFileDescriptor = -1;
            int valueFileDescriptor = -1;
            SetPinEventsToDetect(pinNumber, eventTypes);
            AddPinToPoll(pinNumber, ref valueFileDescriptor, ref pollFileDescriptor, out bool closePinValueFileDescriptor);

            bool eventDetected = WasEventDetected(pollFileDescriptor, valueFileDescriptor, out _, cancellationToken);
P
Patrick Grawehr 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
            if (_statusUpdateSleepTime > TimeSpan.Zero)
            {
                Thread.Sleep(_statusUpdateSleepTime); // Adding some delay to make sure that the value of the File has been updated so that we will get the right event type.
            }

            PinEventTypes detectedEventType = PinEventTypes.None;
            if (eventDetected)
            {
                // This is the only case where we need to read the new state. Although there are reports of this not being 100% reliable in all situations,
                // it seems to be working fine most of the time.
                if (eventTypes == (PinEventTypes.Rising | PinEventTypes.Falling))
                {
                    detectedEventType = (Read(pinNumber) == PinValue.High) ? PinEventTypes.Rising : PinEventTypes.Falling;
                }
                else if (eventTypes != PinEventTypes.None)
                {
                    // If we're only waiting for one event type, we know which one it has to be
                    detectedEventType = eventTypes;
                }
            }
340 341 342 343 344

            RemovePinFromPoll(pinNumber, ref valueFileDescriptor, ref pollFileDescriptor, closePinValueFileDescriptor, closePollFileDescriptor: true, cancelEventDetectionThread: false);
            return new WaitForEventResult
            {
                TimedOut = !eventDetected,
P
Patrick Grawehr 已提交
345
                EventTypes = detectedEventType,
346 347 348
            };
        }

G
Greg Ingram 已提交
349
        private void SetPinEventsToDetect(int pinNumber, PinEventTypes eventTypes)
350
        {
351
            string edgePath = Path.Combine(GpioBasePath, $"gpio{pinNumber + s_pinOffset}", "edge");
P
Patrick Grawehr 已提交
352 353
            // Even though the pin is open, we might sometimes need to wait for access
            SysFsHelpers.EnsureReadWriteAccessToPath(edgePath);
G
Greg Ingram 已提交
354
            string stringValue = PinEventTypeToStringValue(eventTypes);
355 356 357 358 359
            File.WriteAllText(edgePath, stringValue);
        }

        private PinEventTypes GetPinEventsToDetect(int pinNumber)
        {
360
            string edgePath = Path.Combine(GpioBasePath, $"gpio{pinNumber + s_pinOffset}", "edge");
P
Patrick Grawehr 已提交
361 362
            // Even though the pin is open, we might sometimes need to wait for access
            SysFsHelpers.EnsureReadWriteAccessToPath(edgePath);
363 364 365 366 367 368
            string stringValue = File.ReadAllText(edgePath);
            return StringValueToPinEventType(stringValue);
        }

        private PinEventTypes StringValueToPinEventType(string value)
        {
369
            return value.Trim() switch
370
            {
371 372 373 374 375 376
                "none" => PinEventTypes.None,
                "both" => PinEventTypes.Falling | PinEventTypes.Rising,
                "rising" => PinEventTypes.Rising,
                "falling" => PinEventTypes.Falling,
                _ => throw new ArgumentException("Invalid pin event value.", value)
            };
377 378 379 380 381 382 383 384
        }

        private string PinEventTypeToStringValue(PinEventTypes kind)
        {
            if (kind == PinEventTypes.None)
            {
                return "none";
            }
385

386
            if ((kind & PinEventTypes.Falling) != 0 && (kind & PinEventTypes.Rising) != 0)
387 388 389
            {
                return "both";
            }
390

391 392 393 394
            if (kind == PinEventTypes.Rising)
            {
                return "rising";
            }
395

396 397 398 399
            if (kind == PinEventTypes.Falling)
            {
                return "falling";
            }
400

401 402 403 404 405 406 407 408 409 410
            throw new ArgumentException("Invalid Pin Event Type.", nameof(kind));
        }

        private void AddPinToPoll(int pinNumber, ref int valueFileDescriptor, ref int pollFileDescriptor, out bool closePinValueFileDescriptor)
        {
            if (pollFileDescriptor == -1)
            {
                pollFileDescriptor = Interop.epoll_create(1);
                if (pollFileDescriptor < 0)
                {
P
Patrick Grawehr 已提交
411
                    throw new IOException("Error while trying to initialize pin interrupts (epoll_create failed).");
412 413 414 415 416 417 418
                }
            }

            closePinValueFileDescriptor = false;

            if (valueFileDescriptor == -1)
            {
419
                string valuePath = Path.Combine(GpioBasePath, $"gpio{pinNumber + s_pinOffset}", "value");
420 421 422
                valueFileDescriptor = Interop.open(valuePath, FileOpenFlags.O_RDONLY | FileOpenFlags.O_NONBLOCK);
                if (valueFileDescriptor < 0)
                {
P
Patrick Grawehr 已提交
423
                    throw new IOException($"Error while trying to open pin value file {valuePath}.");
424
                }
425

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
                closePinValueFileDescriptor = true;
            }

            epoll_event epollEvent = new epoll_event
            {
                events = PollEvents.EPOLLIN | PollEvents.EPOLLET | PollEvents.EPOLLPRI,
                data = new epoll_data()
                {
                    pinNumber = pinNumber
                }
            };

            int result = Interop.epoll_ctl(pollFileDescriptor, PollOperations.EPOLL_CTL_ADD, valueFileDescriptor, ref epollEvent);
            if (result == -1)
            {
P
Patrick Grawehr 已提交
441
                throw new IOException("Error while trying to initialize pin interrupts (epoll_ctl failed).");
442 443 444 445 446 447 448 449 450 451 452 453 454 455
            }

            // Ignore first time because it will always return the current state.
            Interop.epoll_wait(pollFileDescriptor, out _, 1, 0);
        }

        private unsafe bool WasEventDetected(int pollFileDescriptor, int valueFileDescriptor, out int pinNumber, CancellationToken cancellationToken)
        {
            char buf;
            IntPtr bufPtr = new IntPtr(&buf);
            pinNumber = -1;

            while (!cancellationToken.IsCancellationRequested)
            {
P
Patrick Grawehr 已提交
456 457
                // Wait until something happens
                int waitResult = Interop.epoll_wait(pollFileDescriptor, out epoll_event events, 1, PollingTimeout);
458 459
                if (waitResult == -1)
                {
P
Patrick Grawehr 已提交
460
                    throw new IOException("Error while waiting for pin interrupts.");
461
                }
462

463 464 465 466
                if (waitResult > 0)
                {
                    pinNumber = events.data.pinNumber;

P
Patrick Grawehr 已提交
467 468
                    // This entire section is probably not necessary, but this seems to be hard to validate.
                    // See https://github.com/dotnet/iot/pull/914#discussion_r389924106 and issue #1024.
469 470
                    if (valueFileDescriptor == -1)
                    {
P
Patrick Grawehr 已提交
471
                        // valueFileDescriptor will be -1 when using the callback eventing. For WaitForEvent, the value will be set.
472 473 474 475 476 477
                        valueFileDescriptor = _devicePins[pinNumber].FileDescriptor;
                    }

                    int lseekResult = Interop.lseek(valueFileDescriptor, 0, SeekFlags.SEEK_SET);
                    if (lseekResult == -1)
                    {
P
Patrick Grawehr 已提交
478
                        throw new IOException("Error while trying to seek in value file.");
479 480 481 482 483
                    }

                    int readResult = Interop.read(valueFileDescriptor, bufPtr, 1);
                    if (readResult != 1)
                    {
P
Patrick Grawehr 已提交
484
                        throw new IOException("Error while trying to read value file.");
485
                    }
486

487 488 489
                    return true;
                }
            }
490

491 492 493 494 495 496 497 498 499 500 501 502 503
            return false;
        }

        private void RemovePinFromPoll(int pinNumber, ref int valueFileDescriptor, ref int pollFileDescriptor, bool closePinValueFileDescriptor, bool closePollFileDescriptor, bool cancelEventDetectionThread)
        {
            epoll_event epollEvent = new epoll_event
            {
                events = PollEvents.EPOLLIN | PollEvents.EPOLLET | PollEvents.EPOLLPRI
            };

            int result = Interop.epoll_ctl(pollFileDescriptor, PollOperations.EPOLL_CTL_DEL, valueFileDescriptor, ref epollEvent);
            if (result == -1)
            {
P
Patrick Grawehr 已提交
504
                throw new IOException("Error while trying to delete pin interrupts.");
505 506 507 508 509 510 511
            }

            if (closePinValueFileDescriptor)
            {
                Interop.close(valueFileDescriptor);
                valueFileDescriptor = -1;
            }
512

513 514 515 516
            if (closePollFileDescriptor)
            {
                if (cancelEventDetectionThread)
                {
517 518
                    try
                    {
519 520 521 522 523 524
                        _eventThreadCancellationTokenSource.Cancel();
                    }
                    catch (ObjectDisposedException)
                    {
                    }

525 526 527 528 529 530 531 532 533 534 535
                    while (_eventDetectionThread != null && _eventDetectionThread.IsAlive)
                    {
                        Thread.Sleep(TimeSpan.FromMilliseconds(10)); // Wait until the event detection thread is aborted.
                    }
                }

                Interop.close(pollFileDescriptor);
                pollFileDescriptor = -1;
            }
        }

536
        /// <inheritdoc/>
537 538 539 540 541
        protected override void Dispose(bool disposing)
        {
            _pinsToDetectEventsCount = 0;
            if (_eventDetectionThread != null && _eventDetectionThread.IsAlive)
            {
542 543
                try
                {
544 545 546 547 548 549 550 551
                    _eventThreadCancellationTokenSource.Cancel();
                    _eventThreadCancellationTokenSource.Dispose();
                }
                catch (ObjectDisposedException)
                {
                    // The Cancellation Token source may already be disposed.
                }

552 553 554 555 556
                while (_eventDetectionThread != null && _eventDetectionThread.IsAlive)
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(10)); // Wait until the event detection thread is aborted.
                }
            }
557

558 559 560 561
            foreach (UnixDriverDevicePin devicePin in _devicePins.Values)
            {
                devicePin.Dispose();
            }
562

563 564 565 566 567 568
            _devicePins.Clear();
            if (_pollFileDescriptor != -1)
            {
                Interop.close(_pollFileDescriptor);
                _pollFileDescriptor = -1;
            }
569

570 571 572 573
            while (_exportedPins.Count > 0)
            {
                ClosePin(_exportedPins.FirstOrDefault());
            }
574

575 576 577 578 579 580 581 582 583
            base.Dispose(disposing);
        }

        /// <summary>
        /// Adds a handler for a pin value changed event.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
        /// <param name="eventTypes">The event types to wait for.</param>
        /// <param name="callback">Delegate that defines the structure for callbacks when a pin value changed event occurs.</param>
G
Greg Ingram 已提交
584
        protected internal override void AddCallbackForPinValueChangedEvent(int pinNumber, PinEventTypes eventTypes, PinChangeEventHandler callback)
585 586 587
        {
            if (!_devicePins.ContainsKey(pinNumber))
            {
P
Patrick Grawehr 已提交
588
                _devicePins.Add(pinNumber, new UnixDriverDevicePin(Read(pinNumber)));
589 590 591
                _pinsToDetectEventsCount++;
                AddPinToPoll(pinNumber, ref _devicePins[pinNumber].FileDescriptor, ref _pollFileDescriptor, out _);
            }
592

593
            if ((eventTypes & PinEventTypes.Rising) != 0)
594 595 596
            {
                _devicePins[pinNumber].ValueRising += callback;
            }
597

598
            if ((eventTypes & PinEventTypes.Falling) != 0)
599 600 601
            {
                _devicePins[pinNumber].ValueFalling += callback;
            }
602

P
Patrick Grawehr 已提交
603 604 605 606 607
            PinEventTypes events = (GetPinEventsToDetect(pinNumber) | eventTypes);
            SetPinEventsToDetect(pinNumber, events);

            // Remember which events are active
            _devicePins[pinNumber].ActiveEdges = events;
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
            InitializeEventDetectionThread();
        }

        private void InitializeEventDetectionThread()
        {
            if (_eventDetectionThread == null)
            {
                _eventDetectionThread = new Thread(DetectEvents)
                {
                    IsBackground = true
                };
                _eventDetectionThread.Start();
            }
        }

P
Patrick Grawehr 已提交
623
        private void DetectEvents()
624 625 626
        {
            while (_pinsToDetectEventsCount > 0)
            {
627 628
                try
                {
629
                    bool eventDetected = WasEventDetected(_pollFileDescriptor, -1, out int pinNumber, _eventThreadCancellationTokenSource.Token);
630 631
                    if (eventDetected)
                    {
P
Patrick Grawehr 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
                        if (_statusUpdateSleepTime > TimeSpan.Zero)
                        {
                            Thread.Sleep(_statusUpdateSleepTime); // Adding some delay to make sure that the value of the File has been updated so that we will get the right event type.
                        }

                        PinValue newValue = Read(pinNumber);

                        UnixDriverDevicePin currentPin = _devicePins[pinNumber];
                        PinEventTypes activeEdges = currentPin.ActiveEdges;
                        PinEventTypes eventType = activeEdges;
                        PinEventTypes secondEvent = PinEventTypes.None;
                        // Only if the active edges are both, we need to query the current state and guess about the change
                        if (activeEdges == (PinEventTypes.Falling | PinEventTypes.Rising))
                        {
                            PinValue oldValue = currentPin.LastValue;
                            if (oldValue == PinValue.Low && newValue == PinValue.High)
                            {
                                eventType = PinEventTypes.Rising;
                            }
                            else if (oldValue == PinValue.High && newValue == PinValue.Low)
                            {
                                eventType = PinEventTypes.Falling;
                            }
                            else if (oldValue == PinValue.High)
                            {
                                // Both high -> There must have been a low-active peak
                                eventType = PinEventTypes.Falling;
                                secondEvent = PinEventTypes.Rising;
                            }
                            else
                            {
                                // Both low -> There must have been a high-active peak
                                eventType = PinEventTypes.Rising;
                                secondEvent = PinEventTypes.Falling;
                            }

                            currentPin.LastValue = newValue;
                        }
                        else
                        {
                            // Update the value, in case we need it later
                            currentPin.LastValue = newValue;
                        }

                        PinValueChangedEventArgs args = new PinValueChangedEventArgs(eventType, pinNumber);
                        currentPin.OnPinValueChanged(args);
                        if (secondEvent != PinEventTypes.None)
                        {
                            args = new PinValueChangedEventArgs(secondEvent, pinNumber);
                            currentPin.OnPinValueChanged(args);
                        }
683
                    }
684 685
                }
                catch (ObjectDisposedException)
686
                {
P
Patrick Grawehr 已提交
687
                    break; // If cancellation token source is disposed then we need to exit this thread.
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
                }
            }

            _eventDetectionThread = null;
        }

        /// <summary>
        /// Removes a handler for a pin value changed event.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
        /// <param name="callback">Delegate that defines the structure for callbacks when a pin value changed event occurs.</param>
        protected internal override void RemoveCallbackForPinValueChangedEvent(int pinNumber, PinChangeEventHandler callback)
        {
            if (!_devicePins.ContainsKey(pinNumber))
            {
                throw new InvalidOperationException("Attempted to remove a callback for a pin that is not listening for events.");
            }
705

706 707 708
            _devicePins[pinNumber].ValueFalling -= callback;
            _devicePins[pinNumber].ValueRising -= callback;
            if (_devicePins[pinNumber].IsCallbackListEmpty())
709
            {
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
                _pinsToDetectEventsCount--;

                bool closePollFileDescriptor = (_pinsToDetectEventsCount == 0);
                RemovePinFromPoll(pinNumber, ref _devicePins[pinNumber].FileDescriptor, ref _pollFileDescriptor, true, closePollFileDescriptor, true);
                _devicePins[pinNumber].Dispose();
                _devicePins.Remove(pinNumber);
            }
        }

        /// <summary>
        /// Gets the mode of a pin.
        /// </summary>
        /// <param name="pinNumber">The pin number in the driver's logical numbering scheme.</param>
        /// <returns>The mode of the pin.</returns>
        protected internal override PinMode GetPinMode(int pinNumber)
        {
726
            pinNumber += s_pinOffset;
727 728 729 730 731
            string directionPath = $"{GpioBasePath}/gpio{pinNumber}/direction";
            if (File.Exists(directionPath))
            {
                try
                {
G
Greg Ingram 已提交
732 733
                    string sysFsMode = File.ReadAllText(directionPath);
                    return ConvertSysFsModeToPinMode(sysFsMode);
734 735 736 737 738 739 740 741 742 743 744 745 746
                }
                catch (UnauthorizedAccessException e)
                {
                    throw new UnauthorizedAccessException("Getting a mode to a pin requires root permissions.", e);
                }
            }
            else
            {
                throw new InvalidOperationException("There was an attempt to get a mode to a pin that is not open.");
            }
        }
    }
}