|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Device.Gpio; |
| 7 | +using System.Linq; |
| 8 | +using System.Text; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member |
| 12 | + |
| 13 | +namespace Iot.Device.Gpio |
| 14 | +{ |
| 15 | + /// <summary> |
| 16 | + /// A virtual GPIO controller that serves primarily for a pin mapping on an existing controller. |
| 17 | + /// Unlike <see cref="VirtualGpioController"/> it has a default controller rather than individual pins |
| 18 | + /// and thus also supports <see cref="GpioController.OpenPin(int)"/>. |
| 19 | + /// </summary> |
| 20 | + public class VirtualGpioControllerWithDefault : VirtualGpioController |
| 21 | + { |
| 22 | + private readonly GpioController _defaultController; |
| 23 | + private readonly Dictionary<int, int> _fromVirtualToRealMapping; |
| 24 | + |
| 25 | + public VirtualGpioControllerWithDefault(GpioController defaultController, Dictionary<int, int> fromVirtualToRealMapping) |
| 26 | + { |
| 27 | + _defaultController = defaultController ?? throw new ArgumentNullException(nameof(defaultController)); |
| 28 | + _fromVirtualToRealMapping = fromVirtualToRealMapping ?? throw new ArgumentNullException(nameof(fromVirtualToRealMapping)); |
| 29 | + } |
| 30 | + |
| 31 | + /// <summary> |
| 32 | + /// Opens a pin from the default controller |
| 33 | + /// </summary> |
| 34 | + /// <param name="pinNumber">The pin number</param> |
| 35 | + protected override void OpenPinCore(int pinNumber) |
| 36 | + { |
| 37 | + int realPinNumber = MapToRealPin(pinNumber); |
| 38 | + if (realPinNumber == -1) |
| 39 | + { |
| 40 | + throw new InvalidOperationException($"Virtual Pin Number {pinNumber} is unknown"); |
| 41 | + } |
| 42 | + |
| 43 | + var pin = _defaultController.OpenPin(realPinNumber); |
| 44 | + if (!Add(pinNumber, pin)) |
| 45 | + { |
| 46 | + _defaultController.ClosePin(realPinNumber); |
| 47 | + throw new InvalidOperationException($"Virtual Pin Number {pinNumber} is in use already"); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public int MapToRealPin(int virtualPin) |
| 52 | + { |
| 53 | + if (_fromVirtualToRealMapping.TryGetValue(virtualPin, out int realPin)) |
| 54 | + { |
| 55 | + return realPin; |
| 56 | + } |
| 57 | + |
| 58 | + return -1; |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments