1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- #define STREAM
- using System;
- using System.IO;
- using System.Threading;
- using FunnyCommon.Shared;
- namespace FunnyCommon.Local
- {
- public class PiFileGpout : IPiGpout
- {
- private const string PathExport = "/sys/class/gpio/export";
- private const string PathUnexport = "/sys/class/gpio/unexport";
- private string PathDirection => $"/sys/class/gpio/gpio{_pin}/direction";
- private string PathValue => $"/sys/class/gpio/gpio{_pin}/value";
- #if STREAM
- private Stream _pinStream;
- #endif
- private readonly int _pin;
- public PiFileGpout(int pin)
- {
- _pin = pin;
- Init();
- }
- private void Init()
- {
- File.WriteAllText(PathExport, _pin.ToString());
- Thread.Sleep(100);
- File.WriteAllText(PathDirection, "out");
- #if STREAM
- Thread.Sleep(100);
- _pinStream = new FileStream(PathValue
- , FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
- #endif
- }
- private void Close()
- {
- #if STREAM
- if (_pinStream == null) return;
- _pinStream.Close();
- _pinStream = null;
- #endif
- File.WriteAllText(PathUnexport, _pin.ToString());
- }
- public void WritePin(bool height)
- {
- #if STREAM
- _pinStream.Seek(0, SeekOrigin.Begin);
- _pinStream.WriteByte((byte)(height ? 49 : 48));
- _pinStream.Flush();
- #else
- File.WriteAllText(PathValue, height ? "1" : "0");
- #endif
- }
- public void Dispose()
- {
- Close();
- }
- public static bool Rob(int pin)
- {
- try
- {
- File.WriteAllText(PathUnexport, pin.ToString());
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
- }
- }
|