PiFileGpout.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #define STREAM
  2. using System;
  3. using System.IO;
  4. using System.Threading;
  5. using FunnyCommon.Shared;
  6. namespace FunnyCommon.Local
  7. {
  8. public class PiFileGpout : IPiGpout
  9. {
  10. private const string PathExport = "/sys/class/gpio/export";
  11. private const string PathUnexport = "/sys/class/gpio/unexport";
  12. private string PathDirection => $"/sys/class/gpio/gpio{_pin}/direction";
  13. private string PathValue => $"/sys/class/gpio/gpio{_pin}/value";
  14. #if STREAM
  15. private Stream _pinStream;
  16. #endif
  17. private readonly int _pin;
  18. public PiFileGpout(int pin)
  19. {
  20. _pin = pin;
  21. Init();
  22. }
  23. private void Init()
  24. {
  25. File.WriteAllText(PathExport, _pin.ToString());
  26. Thread.Sleep(100);
  27. File.WriteAllText(PathDirection, "out");
  28. #if STREAM
  29. Thread.Sleep(100);
  30. _pinStream = new FileStream(PathValue
  31. , FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
  32. #endif
  33. }
  34. private void Close()
  35. {
  36. #if STREAM
  37. if (_pinStream == null) return;
  38. _pinStream.Close();
  39. _pinStream = null;
  40. #endif
  41. File.WriteAllText(PathUnexport, _pin.ToString());
  42. }
  43. public void WritePin(bool height)
  44. {
  45. #if STREAM
  46. _pinStream.Seek(0, SeekOrigin.Begin);
  47. _pinStream.WriteByte((byte)(height ? 49 : 48));
  48. _pinStream.Flush();
  49. #else
  50. File.WriteAllText(PathValue, height ? "1" : "0");
  51. #endif
  52. }
  53. public void Dispose()
  54. {
  55. Close();
  56. }
  57. public static bool Rob(int pin)
  58. {
  59. try
  60. {
  61. File.WriteAllText(PathUnexport, pin.ToString());
  62. return true;
  63. }
  64. catch (Exception)
  65. {
  66. return false;
  67. }
  68. }
  69. }
  70. }