Codingstyle....

This commit is contained in:
BlubbFish 2019-12-06 23:12:34 +01:00
parent a7a7278eda
commit b469c4ed6e
22 changed files with 3158 additions and 3245 deletions

View File

@ -1,20 +1,16 @@
namespace Unosquare.RaspberryIO using System;
{
using System; namespace Unosquare.RaspberryIO {
/// <inheritdoc />
/// <inheritdoc /> /// <summary>
/// Occurs when an exception is thrown in the <c>Bluetooth</c> component.
/// </summary>
public class BluetoothErrorException : Exception {
/// <summary> /// <summary>
/// Occurs when an exception is thrown in the <c>Bluetooth</c> component. /// Initializes a new instance of the <see cref="BluetoothErrorException"/> class.
/// </summary> /// </summary>
public class BluetoothErrorException : Exception /// <param name="message">The message.</param>
{ public BluetoothErrorException(String message) : base(message) {
/// <summary> }
/// Initializes a new instance of the <see cref="BluetoothErrorException"/> class. }
/// </summary>
/// <param name="message">The message.</param>
public BluetoothErrorException(string message)
: base(message)
{
}
}
} }

View File

@ -1,134 +1,140 @@
namespace Unosquare.RaspberryIO.Camera using System;
{ using System.Linq;
using System;
using System.Linq; using Swan;
using Swan;
namespace Unosquare.RaspberryIO.Camera {
/// <summary>
/// A simple RGB color class to represent colors in RGB and YUV colorspaces.
/// </summary>
public class CameraColor {
/// <summary> /// <summary>
/// A simple RGB color class to represent colors in RGB and YUV colorspaces. /// Initializes a new instance of the <see cref="CameraColor"/> class.
/// </summary> /// </summary>
public class CameraColor /// <param name="r">The red.</param>
{ /// <param name="g">The green.</param>
/// <summary> /// <param name="b">The blue.</param>
/// Initializes a new instance of the <see cref="CameraColor"/> class. public CameraColor(Int32 r, Int32 g, Int32 b) : this(r, g, b, String.Empty) {
/// </summary> }
/// <param name="r">The red.</param>
/// <param name="g">The green.</param> /// <summary>
/// <param name="b">The blue.</param> /// Initializes a new instance of the <see cref="CameraColor"/> class.
public CameraColor(int r, int g, int b) /// </summary>
: this(r, g, b, string.Empty) /// <param name="r">The red.</param>
{ /// <param name="g">The green.</param>
} /// <param name="b">The blue.</param>
/// <param name="name">The well-known color name.</param>
/// <summary> public CameraColor(Int32 r, Int32 g, Int32 b, String name) {
/// Initializes a new instance of the <see cref="CameraColor"/> class. this.RGB = new[] { Convert.ToByte(r.Clamp(0, 255)), Convert.ToByte(g.Clamp(0, 255)), Convert.ToByte(b.Clamp(0, 255)) };
/// </summary>
/// <param name="r">The red.</param> Single y = this.R * .299000f + this.G * .587000f + this.B * .114000f;
/// <param name="g">The green.</param> Single u = this.R * -.168736f + this.G * -.331264f + this.B * .500000f + 128f;
/// <param name="b">The blue.</param> Single v = this.R * .500000f + this.G * -.418688f + this.B * -.081312f + 128f;
/// <param name="name">The well-known color name.</param>
public CameraColor(int r, int g, int b, string name) this.YUV = new[] { (Byte)y.Clamp(0, 255), (Byte)u.Clamp(0, 255), (Byte)v.Clamp(0, 255) };
{ this.Name = name;
RGB = new[] { Convert.ToByte(r.Clamp(0, 255)), Convert.ToByte(g.Clamp(0, 255)), Convert.ToByte(b.Clamp(0, 255)) }; }
var y = (R * .299000f) + (G * .587000f) + (B * .114000f); #region Static Definitions
var u = (R * -.168736f) + (G * -.331264f) + (B * .500000f) + 128f;
var v = (R * .500000f) + (G * -.418688f) + (B * -.081312f) + 128f; /// <summary>
/// Gets the predefined white color.
YUV = new[] { (byte)y.Clamp(0, 255), (byte)u.Clamp(0, 255), (byte)v.Clamp(0, 255) }; /// </summary>
Name = name; public static CameraColor White => new CameraColor(255, 255, 255, nameof(White));
}
/// <summary>
#region Static Definitions /// Gets the predefined red color.
/// </summary>
/// <summary> public static CameraColor Red => new CameraColor(255, 0, 0, nameof(Red));
/// Gets the predefined white color.
/// </summary> /// <summary>
public static CameraColor White => new CameraColor(255, 255, 255, nameof(White)); /// Gets the predefined green color.
/// </summary>
/// <summary> public static CameraColor Green => new CameraColor(0, 255, 0, nameof(Green));
/// Gets the predefined red color.
/// </summary> /// <summary>
public static CameraColor Red => new CameraColor(255, 0, 0, nameof(Red)); /// Gets the predefined blue color.
/// </summary>
/// <summary> public static CameraColor Blue => new CameraColor(0, 0, 255, nameof(Blue));
/// Gets the predefined green color.
/// </summary> /// <summary>
public static CameraColor Green => new CameraColor(0, 255, 0, nameof(Green)); /// Gets the predefined black color.
/// </summary>
/// <summary> public static CameraColor Black => new CameraColor(0, 0, 0, nameof(Black));
/// Gets the predefined blue color.
/// </summary> #endregion
public static CameraColor Blue => new CameraColor(0, 0, 255, nameof(Blue));
/// <summary>
/// <summary> /// Gets the well-known color name.
/// Gets the predefined black color. /// </summary>
/// </summary> public String Name {
public static CameraColor Black => new CameraColor(0, 0, 0, nameof(Black)); get;
}
#endregion
/// <summary>
/// <summary> /// Gets the red byte.
/// Gets the well-known color name. /// </summary>
/// </summary> public Byte R => this.RGB[0];
public string Name { get; }
/// <summary>
/// <summary> /// Gets the green byte.
/// Gets the red byte. /// </summary>
/// </summary> public Byte G => this.RGB[1];
public byte R => RGB[0];
/// <summary>
/// <summary> /// Gets the blue byte.
/// Gets the green byte. /// </summary>
/// </summary> public Byte B => this.RGB[2];
public byte G => RGB[1];
/// <summary>
/// <summary> /// Gets the RGB byte array (3 bytes).
/// Gets the blue byte. /// </summary>
/// </summary> public Byte[] RGB {
public byte B => RGB[2]; get;
}
/// <summary>
/// Gets the RGB byte array (3 bytes). /// <summary>
/// </summary> /// Gets the YUV byte array (3 bytes).
public byte[] RGB { get; } /// </summary>
public Byte[] YUV {
/// <summary> get;
/// Gets the YUV byte array (3 bytes). }
/// </summary>
public byte[] YUV { get; } /// <summary>
/// Returns a hexadecimal representation of the RGB byte array.
/// <summary> /// Preceded by 0x and all in lowercase.
/// Returns a hexadecimal representation of the RGB byte array. /// </summary>
/// Preceded by 0x and all in lowercase. /// <param name="reverse">if set to <c>true</c> [reverse].</param>
/// </summary> /// <returns>A string.</returns>
/// <param name="reverse">if set to <c>true</c> [reverse].</param> public String ToRgbHex(Boolean reverse) {
/// <returns>A string.</returns> Byte[] data = this.RGB.ToArray();
public string ToRgbHex(bool reverse) if(reverse) {
{ Array.Reverse(data);
var data = RGB.ToArray(); }
if (reverse) Array.Reverse(data);
return ToHex(data); return ToHex(data);
} }
/// <summary> /// <summary>
/// Returns a hexadecimal representation of the YUV byte array. /// Returns a hexadecimal representation of the YUV byte array.
/// Preceded by 0x and all in lowercase. /// Preceded by 0x and all in lowercase.
/// </summary> /// </summary>
/// <param name="reverse">if set to <c>true</c> [reverse].</param> /// <param name="reverse">if set to <c>true</c> [reverse].</param>
/// <returns>A string.</returns> /// <returns>A string.</returns>
public string ToYuvHex(bool reverse) public String ToYuvHex(Boolean reverse) {
{ Byte[] data = this.YUV.ToArray();
var data = YUV.ToArray(); if(reverse) {
if (reverse) Array.Reverse(data); Array.Reverse(data);
return ToHex(data); }
}
return ToHex(data);
/// <summary> }
/// Returns a hexadecimal representation of the data byte array.
/// </summary> /// <summary>
/// <param name="data">The data.</param> /// Returns a hexadecimal representation of the data byte array.
/// <returns>A string.</returns> /// </summary>
private static string ToHex(byte[] data) => $"0x{BitConverter.ToString(data).Replace("-", string.Empty).ToLowerInvariant()}"; /// <param name="data">The data.</param>
} /// <returns>A string.</returns>
private static String ToHex(Byte[] data) => $"0x{BitConverter.ToString(data).Replace("-", String.Empty).ToLowerInvariant()}";
}
} }

View File

@ -1,209 +1,177 @@
namespace Unosquare.RaspberryIO.Camera using System;
{ using System.IO;
using Swan; using System.Threading;
using System; using System.Threading.Tasks;
using System.IO;
using System.Threading; using Swan;
using System.Threading.Tasks;
namespace Unosquare.RaspberryIO.Camera {
/// <summary>
/// The Raspberry Pi's camera controller wrapping raspistill and raspivid programs.
/// This class is a singleton.
/// </summary>
public class CameraController : SingletonBase<CameraController> {
#region Private Declarations
private static readonly ManualResetEventSlim OperationDone = new ManualResetEventSlim(true);
private static readonly Object SyncRoot = new Object();
private static CancellationTokenSource _videoTokenSource = new CancellationTokenSource();
private static Task<Task>? _videoStreamTask;
#endregion
#region Properties
/// <summary> /// <summary>
/// The Raspberry Pi's camera controller wrapping raspistill and raspivid programs. /// Gets a value indicating whether the camera module is busy.
/// This class is a singleton.
/// </summary> /// </summary>
public class CameraController : SingletonBase<CameraController> /// <value>
{ /// <c>true</c> if this instance is busy; otherwise, <c>false</c>.
#region Private Declarations /// </value>
public Boolean IsBusy => OperationDone.IsSet == false;
private static readonly ManualResetEventSlim OperationDone = new ManualResetEventSlim(true);
private static readonly object SyncRoot = new object(); #endregion
private static CancellationTokenSource _videoTokenSource = new CancellationTokenSource();
private static Task<Task>? _videoStreamTask; #region Image Capture Methods
#endregion /// <summary>
/// Captures an image asynchronously.
#region Properties /// </summary>
/// <param name="settings">The settings.</param>
/// <summary> /// <param name="ct">The ct.</param>
/// Gets a value indicating whether the camera module is busy. /// <returns>The image bytes.</returns>
/// </summary> /// <exception cref="InvalidOperationException">Cannot use camera module because it is currently busy.</exception>
/// <value> public async Task<Byte[]> CaptureImageAsync(CameraStillSettings settings, CancellationToken ct = default) {
/// <c>true</c> if this instance is busy; otherwise, <c>false</c>. if(Instance.IsBusy) {
/// </value> throw new InvalidOperationException("Cannot use camera module because it is currently busy.");
public bool IsBusy => OperationDone.IsSet == false; }
#endregion if(settings.CaptureTimeoutMilliseconds <= 0) {
throw new ArgumentException($"{nameof(settings.CaptureTimeoutMilliseconds)} needs to be greater than 0");
#region Image Capture Methods }
/// <summary> try {
/// Captures an image asynchronously. OperationDone.Reset();
/// </summary>
/// <param name="settings">The settings.</param> using MemoryStream output = new MemoryStream();
/// <param name="ct">The ct.</param> Int32 exitCode = await ProcessRunner.RunProcessAsync(settings.CommandName, settings.CreateProcessArguments(), (data, proc) => output.Write(data, 0, data.Length), null, true, ct).ConfigureAwait(false);
/// <returns>The image bytes.</returns>
/// <exception cref="InvalidOperationException">Cannot use camera module because it is currently busy.</exception> return exitCode != 0 ? Array.Empty<Byte>() : output.ToArray();
public async Task<byte[]> CaptureImageAsync(CameraStillSettings settings, CancellationToken ct = default) } finally {
{ OperationDone.Set();
if (Instance.IsBusy) }
throw new InvalidOperationException("Cannot use camera module because it is currently busy."); }
if (settings.CaptureTimeoutMilliseconds <= 0) /// <summary>
throw new ArgumentException($"{nameof(settings.CaptureTimeoutMilliseconds)} needs to be greater than 0"); /// Captures an image.
/// </summary>
try /// <param name="settings">The settings.</param>
{ /// <returns>The image bytes.</returns>
OperationDone.Reset(); public Byte[] CaptureImage(CameraStillSettings settings) => this.CaptureImageAsync(settings).GetAwaiter().GetResult();
using var output = new MemoryStream(); /// <summary>
var exitCode = await ProcessRunner.RunProcessAsync( /// Captures a JPEG encoded image asynchronously at 90% quality.
settings.CommandName, /// </summary>
settings.CreateProcessArguments(), /// <param name="width">The width.</param>
(data, proc) => output.Write(data, 0, data.Length), /// <param name="height">The height.</param>
null, /// <param name="ct">The ct.</param>
true, /// <returns>The image bytes.</returns>
ct).ConfigureAwait(false); public Task<Byte[]> CaptureImageJpegAsync(Int32 width, Int32 height, CancellationToken ct = default) {
CameraStillSettings settings = new CameraStillSettings {
return exitCode != 0 ? Array.Empty<byte>() : output.ToArray(); CaptureWidth = width,
} CaptureHeight = height,
finally CaptureJpegQuality = 90,
{ CaptureTimeoutMilliseconds = 300,
OperationDone.Set(); };
}
} return this.CaptureImageAsync(settings, ct);
}
/// <summary>
/// Captures an image. /// <summary>
/// </summary> /// Captures a JPEG encoded image at 90% quality.
/// <param name="settings">The settings.</param> /// </summary>
/// <returns>The image bytes.</returns> /// <param name="width">The width.</param>
public byte[] CaptureImage(CameraStillSettings settings) => CaptureImageAsync(settings).GetAwaiter().GetResult(); /// <param name="height">The height.</param>
/// <returns>The image bytes.</returns>
/// <summary> public Byte[] CaptureImageJpeg(Int32 width, Int32 height) => this.CaptureImageJpegAsync(width, height).GetAwaiter().GetResult();
/// Captures a JPEG encoded image asynchronously at 90% quality.
/// </summary> #endregion
/// <param name="width">The width.</param>
/// <param name="height">The height.</param> #region Video Capture Methods
/// <param name="ct">The ct.</param>
/// <returns>The image bytes.</returns> /// <summary>
public Task<byte[]> CaptureImageJpegAsync(int width, int height, CancellationToken ct = default) /// Opens the video stream with a timeout of 0 (running indefinitely) at 1080p resolution, variable bitrate and 25 FPS.
{ /// No preview is shown.
var settings = new CameraStillSettings /// </summary>
{ /// <param name="onDataCallback">The on data callback.</param>
CaptureWidth = width, /// <param name="onExitCallback">The on exit callback.</param>
CaptureHeight = height, public void OpenVideoStream(Action<Byte[]> onDataCallback, Action? onExitCallback = null) {
CaptureJpegQuality = 90, CameraVideoSettings settings = new CameraVideoSettings {
CaptureTimeoutMilliseconds = 300, CaptureTimeoutMilliseconds = 0,
}; CaptureDisplayPreview = false,
CaptureWidth = 1920,
return CaptureImageAsync(settings, ct); CaptureHeight = 1080,
} };
/// <summary> this.OpenVideoStream(settings, onDataCallback, onExitCallback);
/// Captures a JPEG encoded image at 90% quality. }
/// </summary>
/// <param name="width">The width.</param> /// <summary>
/// <param name="height">The height.</param> /// Opens the video stream with the supplied settings. Capture Timeout Milliseconds has to be 0 or greater.
/// <returns>The image bytes.</returns> /// </summary>
public byte[] CaptureImageJpeg(int width, int height) => CaptureImageJpegAsync(width, height).GetAwaiter().GetResult(); /// <param name="settings">The settings.</param>
/// <param name="onDataCallback">The on data callback.</param>
#endregion /// <param name="onExitCallback">The on exit callback.</param>
/// <exception cref="InvalidOperationException">Cannot use camera module because it is currently busy.</exception>
#region Video Capture Methods /// <exception cref="ArgumentException">CaptureTimeoutMilliseconds.</exception>
public void OpenVideoStream(CameraVideoSettings settings, Action<Byte[]> onDataCallback, Action? onExitCallback = null) {
/// <summary> if(Instance.IsBusy) {
/// Opens the video stream with a timeout of 0 (running indefinitely) at 1080p resolution, variable bitrate and 25 FPS. throw new InvalidOperationException("Cannot use camera module because it is currently busy.");
/// No preview is shown. }
/// </summary>
/// <param name="onDataCallback">The on data callback.</param> if(settings.CaptureTimeoutMilliseconds < 0) {
/// <param name="onExitCallback">The on exit callback.</param> throw new ArgumentException($"{nameof(settings.CaptureTimeoutMilliseconds)} needs to be greater than or equal to 0");
public void OpenVideoStream(Action<byte[]> onDataCallback, Action? onExitCallback = null) }
{
var settings = new CameraVideoSettings try {
{ OperationDone.Reset();
CaptureTimeoutMilliseconds = 0, _videoStreamTask = Task.Factory.StartNew(() => VideoWorkerDoWork(settings, onDataCallback, onExitCallback), _videoTokenSource.Token);
CaptureDisplayPreview = false, } catch {
CaptureWidth = 1920, OperationDone.Set();
CaptureHeight = 1080, throw;
}; }
}
OpenVideoStream(settings, onDataCallback, onExitCallback);
} /// <summary>
/// Closes the video stream of a video stream is open.
/// <summary> /// </summary>
/// Opens the video stream with the supplied settings. Capture Timeout Milliseconds has to be 0 or greater. public void CloseVideoStream() {
/// </summary> lock(SyncRoot) {
/// <param name="settings">The settings.</param> if(this.IsBusy == false) {
/// <param name="onDataCallback">The on data callback.</param> return;
/// <param name="onExitCallback">The on exit callback.</param> }
/// <exception cref="InvalidOperationException">Cannot use camera module because it is currently busy.</exception> }
/// <exception cref="ArgumentException">CaptureTimeoutMilliseconds.</exception>
public void OpenVideoStream(CameraVideoSettings settings, Action<byte[]> onDataCallback, Action? onExitCallback = null) if(_videoTokenSource.IsCancellationRequested == false) {
{ _videoTokenSource.Cancel();
if (Instance.IsBusy) _videoStreamTask?.Wait();
throw new InvalidOperationException("Cannot use camera module because it is currently busy."); }
if (settings.CaptureTimeoutMilliseconds < 0) _videoTokenSource = new CancellationTokenSource();
throw new ArgumentException($"{nameof(settings.CaptureTimeoutMilliseconds)} needs to be greater than or equal to 0"); }
try private static async Task VideoWorkerDoWork(CameraVideoSettings settings, Action<Byte[]> onDataCallback, Action? onExitCallback) {
{ try {
OperationDone.Reset(); _ = await ProcessRunner.RunProcessAsync(settings.CommandName, settings.CreateProcessArguments(), (data, proc) => onDataCallback?.Invoke(data), null, true, _videoTokenSource.Token).ConfigureAwait(false);
_videoStreamTask = Task.Factory.StartNew(() => VideoWorkerDoWork(settings, onDataCallback, onExitCallback), _videoTokenSource.Token);
} onExitCallback?.Invoke();
catch } catch {
{ // swallow
OperationDone.Set(); } finally {
throw; Instance.CloseVideoStream();
} OperationDone.Set();
} }
}
/// <summary> #endregion
/// Closes the video stream of a video stream is open. }
/// </summary>
public void CloseVideoStream()
{
lock (SyncRoot)
{
if (IsBusy == false)
return;
}
if (_videoTokenSource.IsCancellationRequested == false)
{
_videoTokenSource.Cancel();
_videoStreamTask?.Wait();
}
_videoTokenSource = new CancellationTokenSource();
}
private static async Task VideoWorkerDoWork(
CameraVideoSettings settings,
Action<byte[]> onDataCallback,
Action onExitCallback)
{
try
{
await ProcessRunner.RunProcessAsync(
settings.CommandName,
settings.CreateProcessArguments(),
(data, proc) => onDataCallback?.Invoke(data),
null,
true,
_videoTokenSource.Token).ConfigureAwait(false);
onExitCallback?.Invoke();
}
catch
{
// swallow
}
finally
{
Instance.CloseVideoStream();
OperationDone.Set();
}
}
#endregion
}
} }

View File

@ -1,82 +1,87 @@
namespace Unosquare.RaspberryIO.Camera using System;
{ using System.Globalization;
using System.Globalization;
using Swan; using Swan;
namespace Unosquare.RaspberryIO.Camera {
/// <summary>
/// Defines the Raspberry Pi camera's sensor ROI (Region of Interest).
/// </summary>
public struct CameraRect {
/// <summary> /// <summary>
/// Defines the Raspberry Pi camera's sensor ROI (Region of Interest). /// The default ROI which is the entire area.
/// </summary> /// </summary>
public struct CameraRect public static readonly CameraRect Default = new CameraRect { X = 0M, Y = 0M, W = 1.0M, H = 1.0M };
{
/// <summary> /// <summary>
/// The default ROI which is the entire area. /// Gets or sets the x in relative coordinates. (0.0 to 1.0).
/// </summary> /// </summary>
public static readonly CameraRect Default = new CameraRect { X = 0M, Y = 0M, W = 1.0M, H = 1.0M }; /// <value>
/// The x.
/// <summary> /// </value>
/// Gets or sets the x in relative coordinates. (0.0 to 1.0). public Decimal X {
/// </summary> get; set;
/// <value> }
/// The x.
/// </value> /// <summary>
public decimal X { get; set; } /// Gets or sets the y location in relative coordinates. (0.0 to 1.0).
/// </summary>
/// <summary> /// <value>
/// Gets or sets the y location in relative coordinates. (0.0 to 1.0). /// The y.
/// </summary> /// </value>
/// <value> public Decimal Y {
/// The y. get; set;
/// </value> }
public decimal Y { get; set; }
/// <summary>
/// <summary> /// Gets or sets the width in relative coordinates. (0.0 to 1.0).
/// Gets or sets the width in relative coordinates. (0.0 to 1.0). /// </summary>
/// </summary> /// <value>
/// <value> /// The w.
/// The w. /// </value>
/// </value> public Decimal W {
public decimal W { get; set; } get; set;
}
/// <summary>
/// Gets or sets the height in relative coordinates. (0.0 to 1.0). /// <summary>
/// </summary> /// Gets or sets the height in relative coordinates. (0.0 to 1.0).
/// <value> /// </summary>
/// The h. /// <value>
/// </value> /// The h.
public decimal H { get; set; } /// </value>
public Decimal H {
/// <summary> get; set;
/// Gets a value indicating whether this instance is equal to the default (The entire area). }
/// </summary>
/// <value> /// <summary>
/// <c>true</c> if this instance is default; otherwise, <c>false</c>. /// Gets a value indicating whether this instance is equal to the default (The entire area).
/// </value> /// </summary>
public bool IsDefault /// <value>
{ /// <c>true</c> if this instance is default; otherwise, <c>false</c>.
get /// </value>
{ public Boolean IsDefault {
Clamp(); get {
return X == Default.X && Y == Default.Y && W == Default.W && H == Default.H; this.Clamp();
} return this.X == Default.X && this.Y == Default.Y && this.W == Default.W && this.H == Default.H;
} }
}
/// <summary>
/// Clamps the members of this ROI to their minimum and maximum values. /// <summary>
/// </summary> /// Clamps the members of this ROI to their minimum and maximum values.
public void Clamp() /// </summary>
{ public void Clamp() {
X = X.Clamp(0M, 1M); this.X = this.X.Clamp(0M, 1M);
Y = Y.Clamp(0M, 1M); this.Y = this.Y.Clamp(0M, 1M);
W = W.Clamp(0M, 1M - X); this.W = this.W.Clamp(0M, 1M - this.X);
H = H.Clamp(0M, 1M - Y); this.H = this.H.Clamp(0M, 1M - this.Y);
} }
/// <summary> /// <summary>
/// Returns a <see cref="string" /> that represents this instance. /// Returns a <see cref="String" /> that represents this instance.
/// </summary> /// </summary>
/// <returns> /// <returns>
/// A <see cref="string" /> that represents this instance. /// A <see cref="String" /> that represents this instance.
/// </returns> /// </returns>
public override string ToString() => $"{X.ToString(CultureInfo.InvariantCulture)},{Y.ToString(CultureInfo.InvariantCulture)},{W.ToString(CultureInfo.InvariantCulture)},{H.ToString(CultureInfo.InvariantCulture)}"; public override String ToString() => $"{this.X.ToString(CultureInfo.InvariantCulture)},{this.Y.ToString(CultureInfo.InvariantCulture)},{this.W.ToString(CultureInfo.InvariantCulture)},{this.H.ToString(CultureInfo.InvariantCulture)}";
} }
} }

View File

@ -1,340 +1,361 @@
namespace Unosquare.RaspberryIO.Camera using System;
{ using System.Globalization;
using System.Globalization; using System.Text;
using System.Text;
using Swan; using Swan;
namespace Unosquare.RaspberryIO.Camera {
/// <summary>
/// A base class to implement raspistill and raspivid wrappers
/// Full documentation available at
/// https://www.raspberrypi.org/documentation/raspbian/applications/camera.md.
/// </summary>
public abstract class CameraSettingsBase {
/// <summary> /// <summary>
/// A base class to implement raspistill and raspivid wrappers /// The Invariant Culture shorthand.
/// Full documentation available at
/// https://www.raspberrypi.org/documentation/raspbian/applications/camera.md.
/// </summary> /// </summary>
public abstract class CameraSettingsBase protected static readonly CultureInfo Ci = CultureInfo.InvariantCulture;
{
/// <summary> #region Capture Settings
/// The Invariant Culture shorthand.
/// </summary> /// <summary>
protected static readonly CultureInfo Ci = CultureInfo.InvariantCulture; /// Gets or sets the timeout milliseconds.
/// Default value is 5000
#region Capture Settings /// Recommended value is at least 300 in order to let the light collectors open.
/// </summary>
/// <summary> public Int32 CaptureTimeoutMilliseconds { get; set; } = 5000;
/// Gets or sets the timeout milliseconds.
/// Default value is 5000 /// <summary>
/// Recommended value is at least 300 in order to let the light collectors open. /// Gets or sets a value indicating whether or not to show a preview window on the screen.
/// </summary> /// </summary>
public int CaptureTimeoutMilliseconds { get; set; } = 5000; public Boolean CaptureDisplayPreview { get; set; } = false;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether or not to show a preview window on the screen. /// Gets or sets a value indicating whether a preview window is shown in full screen mode if enabled.
/// </summary> /// </summary>
public bool CaptureDisplayPreview { get; set; } = false; public Boolean CaptureDisplayPreviewInFullScreen { get; set; } = true;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether a preview window is shown in full screen mode if enabled. /// Gets or sets a value indicating whether video stabilization should be enabled.
/// </summary> /// </summary>
public bool CaptureDisplayPreviewInFullScreen { get; set; } = true; public Boolean CaptureVideoStabilizationEnabled { get; set; } = false;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether video stabilization should be enabled. /// Gets or sets the display preview opacity only if the display preview property is enabled.
/// </summary> /// </summary>
public bool CaptureVideoStabilizationEnabled { get; set; } = false; public Byte CaptureDisplayPreviewOpacity { get; set; } = 255;
/// <summary> /// <summary>
/// Gets or sets the display preview opacity only if the display preview property is enabled. /// Gets or sets the capture sensor region of interest in relative coordinates.
/// </summary> /// </summary>
public byte CaptureDisplayPreviewOpacity { get; set; } = 255; public CameraRect CaptureSensorRoi { get; set; } = CameraRect.Default;
/// <summary> /// <summary>
/// Gets or sets the capture sensor region of interest in relative coordinates. /// Gets or sets the capture shutter speed in microseconds.
/// </summary> /// Default -1, Range 0 to 6000000 (equivalent to 6 seconds).
public CameraRect CaptureSensorRoi { get; set; } = CameraRect.Default; /// </summary>
public Int32 CaptureShutterSpeedMicroseconds { get; set; } = -1;
/// <summary>
/// Gets or sets the capture shutter speed in microseconds. /// <summary>
/// Default -1, Range 0 to 6000000 (equivalent to 6 seconds). /// Gets or sets the exposure mode.
/// </summary> /// </summary>
public int CaptureShutterSpeedMicroseconds { get; set; } = -1; public CameraExposureMode CaptureExposure { get; set; } = CameraExposureMode.Auto;
/// <summary> /// <summary>
/// Gets or sets the exposure mode. /// Gets or sets the picture EV compensation. Default is 0, Range is -10 to 10
/// </summary> /// Camera exposure compensation is commonly stated in terms of EV units;
public CameraExposureMode CaptureExposure { get; set; } = CameraExposureMode.Auto; /// 1 EV is equal to one exposure step (or stop), corresponding to a doubling of exposure.
/// Exposure can be adjusted by changing either the lens f-number or the exposure time;
/// <summary> /// which one is changed usually depends on the camera's exposure mode.
/// Gets or sets the picture EV compensation. Default is 0, Range is -10 to 10 /// </summary>
/// Camera exposure compensation is commonly stated in terms of EV units; public Int32 CaptureExposureCompensation { get; set; } = 0;
/// 1 EV is equal to one exposure step (or stop), corresponding to a doubling of exposure.
/// Exposure can be adjusted by changing either the lens f-number or the exposure time; /// <summary>
/// which one is changed usually depends on the camera's exposure mode. /// Gets or sets the capture metering mode.
/// </summary> /// </summary>
public int CaptureExposureCompensation { get; set; } = 0; public CameraMeteringMode CaptureMeteringMode { get; set; } = CameraMeteringMode.Average;
/// <summary> /// <summary>
/// Gets or sets the capture metering mode. /// Gets or sets the automatic white balance mode. By default it is set to Auto.
/// </summary> /// </summary>
public CameraMeteringMode CaptureMeteringMode { get; set; } = CameraMeteringMode.Average; public CameraWhiteBalanceMode CaptureWhiteBalanceControl { get; set; } = CameraWhiteBalanceMode.Auto;
/// <summary> /// <summary>
/// Gets or sets the automatic white balance mode. By default it is set to Auto. /// Gets or sets the capture white balance gain on the blue channel. Example: 1.25
/// </summary> /// Only takes effect if White balance control is set to off.
public CameraWhiteBalanceMode CaptureWhiteBalanceControl { get; set; } = CameraWhiteBalanceMode.Auto; /// Default is 0.
/// </summary>
/// <summary> public Decimal CaptureWhiteBalanceGainBlue { get; set; } = 0M;
/// Gets or sets the capture white balance gain on the blue channel. Example: 1.25
/// Only takes effect if White balance control is set to off. /// <summary>
/// Default is 0. /// Gets or sets the capture white balance gain on the red channel. Example: 1.75
/// </summary> /// Only takes effect if White balance control is set to off.
public decimal CaptureWhiteBalanceGainBlue { get; set; } = 0M; /// Default is 0.
/// </summary>
/// <summary> public Decimal CaptureWhiteBalanceGainRed { get; set; } = 0M;
/// Gets or sets the capture white balance gain on the red channel. Example: 1.75
/// Only takes effect if White balance control is set to off. /// <summary>
/// Default is 0. /// Gets or sets the dynamic range compensation.
/// </summary> /// DRC changes the images by increasing the range of dark areas, and decreasing the brighter areas. This can improve the image in low light areas.
public decimal CaptureWhiteBalanceGainRed { get; set; } = 0M; /// </summary>
public CameraDynamicRangeCompensation CaptureDynamicRangeCompensation {
/// <summary> get; set;
/// Gets or sets the dynamic range compensation. } = CameraDynamicRangeCompensation.Off;
/// DRC changes the images by increasing the range of dark areas, and decreasing the brighter areas. This can improve the image in low light areas.
/// </summary> #endregion
public CameraDynamicRangeCompensation CaptureDynamicRangeCompensation { get; set; } =
CameraDynamicRangeCompensation.Off; #region Image Properties
#endregion /// <summary>
/// Gets or sets the width of the picture to take.
#region Image Properties /// Less than or equal to 0 in either width or height means maximum resolution available.
/// </summary>
/// <summary> public Int32 CaptureWidth { get; set; } = 640;
/// Gets or sets the width of the picture to take.
/// Less than or equal to 0 in either width or height means maximum resolution available. /// <summary>
/// </summary> /// Gets or sets the height of the picture to take.
public int CaptureWidth { get; set; } = 640; /// Less than or equal to 0 in either width or height means maximum resolution available.
/// </summary>
/// <summary> public Int32 CaptureHeight { get; set; } = 480;
/// Gets or sets the height of the picture to take.
/// Less than or equal to 0 in either width or height means maximum resolution available. /// <summary>
/// </summary> /// Gets or sets the picture sharpness. Default is 0, Range form -100 to 100.
public int CaptureHeight { get; set; } = 480; /// </summary>
public Int32 ImageSharpness { get; set; } = 0;
/// <summary>
/// Gets or sets the picture sharpness. Default is 0, Range form -100 to 100. /// <summary>
/// </summary> /// Gets or sets the picture contrast. Default is 0, Range form -100 to 100.
public int ImageSharpness { get; set; } = 0; /// </summary>
public Int32 ImageContrast { get; set; } = 0;
/// <summary>
/// Gets or sets the picture contrast. Default is 0, Range form -100 to 100. /// <summary>
/// </summary> /// Gets or sets the picture brightness. Default is 50, Range form 0 to 100.
public int ImageContrast { get; set; } = 0; /// </summary>
public Int32 ImageBrightness { get; set; } = 50; // from 0 to 100
/// <summary>
/// Gets or sets the picture brightness. Default is 50, Range form 0 to 100. /// <summary>
/// </summary> /// Gets or sets the picture saturation. Default is 0, Range form -100 to 100.
public int ImageBrightness { get; set; } = 50; // from 0 to 100 /// </summary>
public Int32 ImageSaturation { get; set; } = 0;
/// <summary>
/// Gets or sets the picture saturation. Default is 0, Range form -100 to 100. /// <summary>
/// </summary> /// Gets or sets the picture ISO. Default is -1 Range is 100 to 800
public int ImageSaturation { get; set; } = 0; /// The higher the value, the more light the sensor absorbs.
/// </summary>
/// <summary> public Int32 ImageIso { get; set; } = -1;
/// Gets or sets the picture ISO. Default is -1 Range is 100 to 800
/// The higher the value, the more light the sensor absorbs. /// <summary>
/// </summary> /// Gets or sets the image capture effect to be applied.
public int ImageIso { get; set; } = -1; /// </summary>
public CameraImageEffect ImageEffect { get; set; } = CameraImageEffect.None;
/// <summary>
/// Gets or sets the image capture effect to be applied. /// <summary>
/// </summary> /// Gets or sets the color effect U coordinates.
public CameraImageEffect ImageEffect { get; set; } = CameraImageEffect.None; /// Default is -1, Range is 0 to 255
/// 128:128 should be effectively a monochrome image.
/// <summary> /// </summary>
/// Gets or sets the color effect U coordinates. public Int32 ImageColorEffectU { get; set; } = -1; // 0 to 255
/// Default is -1, Range is 0 to 255
/// 128:128 should be effectively a monochrome image. /// <summary>
/// </summary> /// Gets or sets the color effect V coordinates.
public int ImageColorEffectU { get; set; } = -1; // 0 to 255 /// Default is -1, Range is 0 to 255
/// 128:128 should be effectively a monochrome image.
/// <summary> /// </summary>
/// Gets or sets the color effect V coordinates. public Int32 ImageColorEffectV { get; set; } = -1; // 0 to 255
/// Default is -1, Range is 0 to 255
/// 128:128 should be effectively a monochrome image. /// <summary>
/// </summary> /// Gets or sets the image rotation. Default is no rotation.
public int ImageColorEffectV { get; set; } = -1; // 0 to 255 /// </summary>
public CameraImageRotation ImageRotation { get; set; } = CameraImageRotation.None;
/// <summary>
/// Gets or sets the image rotation. Default is no rotation. /// <summary>
/// </summary> /// Gets or sets a value indicating whether the image should be flipped horizontally.
public CameraImageRotation ImageRotation { get; set; } = CameraImageRotation.None; /// </summary>
public Boolean ImageFlipHorizontally {
/// <summary> get; set;
/// Gets or sets a value indicating whether the image should be flipped horizontally. }
/// </summary>
public bool ImageFlipHorizontally { get; set; } /// <summary>
/// Gets or sets a value indicating whether the image should be flipped vertically.
/// <summary> /// </summary>
/// Gets or sets a value indicating whether the image should be flipped vertically. public Boolean ImageFlipVertically {
/// </summary> get; set;
public bool ImageFlipVertically { get; set; } }
/// <summary> /// <summary>
/// Gets or sets the image annotations using a bitmask (or flags) notation. /// Gets or sets the image annotations using a bitmask (or flags) notation.
/// Apply a bitwise OR to the enumeration to include multiple annotations. /// Apply a bitwise OR to the enumeration to include multiple annotations.
/// </summary> /// </summary>
public CameraAnnotation ImageAnnotations { get; set; } = CameraAnnotation.None; public CameraAnnotation ImageAnnotations { get; set; } = CameraAnnotation.None;
/// <summary> /// <summary>
/// Gets or sets the image annotations text. /// Gets or sets the image annotations text.
/// Text may include date/time placeholders by using the '%' character, as used by strftime. /// Text may include date/time placeholders by using the '%' character, as used by strftime.
/// Example: ABC %Y-%m-%d %X will output ABC 2015-10-28 20:09:33. /// Example: ABC %Y-%m-%d %X will output ABC 2015-10-28 20:09:33.
/// </summary> /// </summary>
public string ImageAnnotationsText { get; set; } = string.Empty; public String ImageAnnotationsText { get; set; } = String.Empty;
/// <summary> /// <summary>
/// Gets or sets the font size of the text annotations /// Gets or sets the font size of the text annotations
/// Default is -1, range is 6 to 160. /// Default is -1, range is 6 to 160.
/// </summary> /// </summary>
public int ImageAnnotationFontSize { get; set; } = -1; public Int32 ImageAnnotationFontSize { get; set; } = -1;
/// <summary> /// <summary>
/// Gets or sets the color of the text annotations. /// Gets or sets the color of the text annotations.
/// </summary> /// </summary>
/// <value> /// <value>
/// The color of the image annotation font. /// The color of the image annotation font.
/// </value> /// </value>
public CameraColor? ImageAnnotationFontColor { get; set; } = null; public CameraColor? ImageAnnotationFontColor { get; set; } = null;
/// <summary> /// <summary>
/// Gets or sets the background color for text annotations. /// Gets or sets the background color for text annotations.
/// </summary> /// </summary>
/// <value> /// <value>
/// The image annotation background. /// The image annotation background.
/// </value> /// </value>
public CameraColor? ImageAnnotationBackground { get; set; } = null; public CameraColor? ImageAnnotationBackground { get; set; } = null;
#endregion #endregion
#region Interface #region Interface
/// <summary> /// <summary>
/// Gets the command file executable. /// Gets the command file executable.
/// </summary> /// </summary>
public abstract string CommandName { get; } public abstract String CommandName {
get;
/// <summary> }
/// Creates the process arguments.
/// </summary> /// <summary>
/// <returns>The string that represents the process arguments.</returns> /// Creates the process arguments.
public virtual string CreateProcessArguments() /// </summary>
{ /// <returns>The string that represents the process arguments.</returns>
var sb = new StringBuilder(); public virtual String CreateProcessArguments() {
sb.Append("-o -"); // output to standard output as opposed to a file. StringBuilder sb = new StringBuilder();
sb.Append($" -t {(CaptureTimeoutMilliseconds < 0 ? "0" : CaptureTimeoutMilliseconds.ToString(Ci))}"); _ = sb.Append("-o -"); // output to standard output as opposed to a file.
_ = sb.Append($" -t {(this.CaptureTimeoutMilliseconds < 0 ? "0" : this.CaptureTimeoutMilliseconds.ToString(Ci))}");
// Basic Width and height
if (CaptureWidth > 0 && CaptureHeight > 0) // Basic Width and height
{ if(this.CaptureWidth > 0 && this.CaptureHeight > 0) {
sb.Append($" -w {CaptureWidth.ToString(Ci)}"); _ = sb.Append($" -w {this.CaptureWidth.ToString(Ci)}");
sb.Append($" -h {CaptureHeight.ToString(Ci)}"); _ = sb.Append($" -h {this.CaptureHeight.ToString(Ci)}");
} }
// Display Preview // Display Preview
if (CaptureDisplayPreview) if(this.CaptureDisplayPreview) {
{ if(this.CaptureDisplayPreviewInFullScreen) {
if (CaptureDisplayPreviewInFullScreen) _ = sb.Append(" -f");
sb.Append(" -f"); }
if (CaptureDisplayPreviewOpacity != byte.MaxValue) if(this.CaptureDisplayPreviewOpacity != Byte.MaxValue) {
sb.Append($" -op {CaptureDisplayPreviewOpacity.ToString(Ci)}"); _ = sb.Append($" -op {this.CaptureDisplayPreviewOpacity.ToString(Ci)}");
} }
else } else {
{ _ = sb.Append(" -n"); // no preview
sb.Append(" -n"); // no preview }
}
// Picture Settings
// Picture Settings if(this.ImageSharpness != 0) {
if (ImageSharpness != 0) _ = sb.Append($" -sh {this.ImageSharpness.Clamp(-100, 100).ToString(Ci)}");
sb.Append($" -sh {ImageSharpness.Clamp(-100, 100).ToString(Ci)}"); }
if (ImageContrast != 0) if(this.ImageContrast != 0) {
sb.Append($" -co {ImageContrast.Clamp(-100, 100).ToString(Ci)}"); _ = sb.Append($" -co {this.ImageContrast.Clamp(-100, 100).ToString(Ci)}");
}
if (ImageBrightness != 50)
sb.Append($" -br {ImageBrightness.Clamp(0, 100).ToString(Ci)}"); if(this.ImageBrightness != 50) {
_ = sb.Append($" -br {this.ImageBrightness.Clamp(0, 100).ToString(Ci)}");
if (ImageSaturation != 0) }
sb.Append($" -sa {ImageSaturation.Clamp(-100, 100).ToString(Ci)}");
if(this.ImageSaturation != 0) {
if (ImageIso >= 100) _ = sb.Append($" -sa {this.ImageSaturation.Clamp(-100, 100).ToString(Ci)}");
sb.Append($" -ISO {ImageIso.Clamp(100, 800).ToString(Ci)}"); }
if (CaptureVideoStabilizationEnabled) if(this.ImageIso >= 100) {
sb.Append(" -vs"); _ = sb.Append($" -ISO {this.ImageIso.Clamp(100, 800).ToString(Ci)}");
}
if (CaptureExposureCompensation != 0)
sb.Append($" -ev {CaptureExposureCompensation.Clamp(-10, 10).ToString(Ci)}"); if(this.CaptureVideoStabilizationEnabled) {
_ = sb.Append(" -vs");
if (CaptureExposure != CameraExposureMode.Auto) }
sb.Append($" -ex {CaptureExposure.ToString().ToLowerInvariant()}");
if(this.CaptureExposureCompensation != 0) {
if (CaptureWhiteBalanceControl != CameraWhiteBalanceMode.Auto) _ = sb.Append($" -ev {this.CaptureExposureCompensation.Clamp(-10, 10).ToString(Ci)}");
sb.Append($" -awb {CaptureWhiteBalanceControl.ToString().ToLowerInvariant()}"); }
if (ImageEffect != CameraImageEffect.None) if(this.CaptureExposure != CameraExposureMode.Auto) {
sb.Append($" -ifx {ImageEffect.ToString().ToLowerInvariant()}"); _ = sb.Append($" -ex {this.CaptureExposure.ToString().ToLowerInvariant()}");
}
if (ImageColorEffectU >= 0 && ImageColorEffectV >= 0)
{ if(this.CaptureWhiteBalanceControl != CameraWhiteBalanceMode.Auto) {
sb.Append( _ = sb.Append($" -awb {this.CaptureWhiteBalanceControl.ToString().ToLowerInvariant()}");
$" -cfx {ImageColorEffectU.Clamp(0, 255).ToString(Ci)}:{ImageColorEffectV.Clamp(0, 255).ToString(Ci)}"); }
}
if(this.ImageEffect != CameraImageEffect.None) {
if (CaptureMeteringMode != CameraMeteringMode.Average) _ = sb.Append($" -ifx {this.ImageEffect.ToString().ToLowerInvariant()}");
sb.Append($" -mm {CaptureMeteringMode.ToString().ToLowerInvariant()}"); }
if (ImageRotation != CameraImageRotation.None) if(this.ImageColorEffectU >= 0 && this.ImageColorEffectV >= 0) {
sb.Append($" -rot {((int)ImageRotation).ToString(Ci)}"); _ = sb.Append(
$" -cfx {this.ImageColorEffectU.Clamp(0, 255).ToString(Ci)}:{this.ImageColorEffectV.Clamp(0, 255).ToString(Ci)}");
if (ImageFlipHorizontally) }
sb.Append(" -hf");
if(this.CaptureMeteringMode != CameraMeteringMode.Average) {
if (ImageFlipVertically) _ = sb.Append($" -mm {this.CaptureMeteringMode.ToString().ToLowerInvariant()}");
sb.Append(" -vf"); }
if (CaptureSensorRoi.IsDefault == false) if(this.ImageRotation != CameraImageRotation.None) {
sb.Append($" -roi {CaptureSensorRoi}"); _ = sb.Append($" -rot {((Int32)this.ImageRotation).ToString(Ci)}");
}
if (CaptureShutterSpeedMicroseconds > 0)
sb.Append($" -ss {CaptureShutterSpeedMicroseconds.Clamp(0, 6000000).ToString(Ci)}"); if(this.ImageFlipHorizontally) {
_ = sb.Append(" -hf");
if (CaptureDynamicRangeCompensation != CameraDynamicRangeCompensation.Off) }
sb.Append($" -drc {CaptureDynamicRangeCompensation.ToString().ToLowerInvariant()}");
if(this.ImageFlipVertically) {
if (CaptureWhiteBalanceControl == CameraWhiteBalanceMode.Off && _ = sb.Append(" -vf");
(CaptureWhiteBalanceGainBlue != 0M || CaptureWhiteBalanceGainRed != 0M)) }
sb.Append($" -awbg {CaptureWhiteBalanceGainBlue.ToString(Ci)},{CaptureWhiteBalanceGainRed.ToString(Ci)}");
if(this.CaptureSensorRoi.IsDefault == false) {
if (ImageAnnotationFontSize > 0) _ = sb.Append($" -roi {this.CaptureSensorRoi}");
{ }
sb.Append($" -ae {ImageAnnotationFontSize.Clamp(6, 160).ToString(Ci)}");
sb.Append($",{(ImageAnnotationFontColor == null ? "0xff" : ImageAnnotationFontColor.ToYuvHex(true))}"); if(this.CaptureShutterSpeedMicroseconds > 0) {
_ = sb.Append($" -ss {this.CaptureShutterSpeedMicroseconds.Clamp(0, 6000000).ToString(Ci)}");
if (ImageAnnotationBackground != null) }
{
ImageAnnotations |= CameraAnnotation.SolidBackground; if(this.CaptureDynamicRangeCompensation != CameraDynamicRangeCompensation.Off) {
sb.Append($",{ImageAnnotationBackground.ToYuvHex(true)}"); _ = sb.Append($" -drc {this.CaptureDynamicRangeCompensation.ToString().ToLowerInvariant()}");
} }
}
if(this.CaptureWhiteBalanceControl == CameraWhiteBalanceMode.Off &&
if (ImageAnnotations != CameraAnnotation.None) (this.CaptureWhiteBalanceGainBlue != 0M || this.CaptureWhiteBalanceGainRed != 0M)) {
sb.Append($" -a {((int)ImageAnnotations).ToString(Ci)}"); _ = sb.Append($" -awbg {this.CaptureWhiteBalanceGainBlue.ToString(Ci)},{this.CaptureWhiteBalanceGainRed.ToString(Ci)}");
}
if (string.IsNullOrWhiteSpace(ImageAnnotationsText) == false)
sb.Append($" -a \"{ImageAnnotationsText.Replace("\"", "'")}\""); if(this.ImageAnnotationFontSize > 0) {
_ = sb.Append($" -ae {this.ImageAnnotationFontSize.Clamp(6, 160).ToString(Ci)}");
return sb.ToString(); _ = sb.Append($",{(this.ImageAnnotationFontColor == null ? "0xff" : this.ImageAnnotationFontColor.ToYuvHex(true))}");
}
if(this.ImageAnnotationBackground != null) {
#endregion this.ImageAnnotations |= CameraAnnotation.SolidBackground;
} _ = sb.Append($",{this.ImageAnnotationBackground.ToYuvHex(true)}");
}
}
if(this.ImageAnnotations != CameraAnnotation.None) {
_ = sb.Append($" -a {((Int32)this.ImageAnnotations).ToString(Ci)}");
}
if(String.IsNullOrWhiteSpace(this.ImageAnnotationsText) == false) {
_ = sb.Append($" -a \"{this.ImageAnnotationsText.Replace("\"", "'")}\"");
}
return sb.ToString();
}
#endregion
}
} }

View File

@ -1,120 +1,122 @@
namespace Unosquare.RaspberryIO.Camera using System;
{ using System.Collections.Generic;
using System; using System.Text;
using System.Collections.Generic;
using System.Text; using Swan;
using Swan;
namespace Unosquare.RaspberryIO.Camera {
/// <summary>
/// Defines a wrapper for the raspistill program and its settings (command-line arguments).
/// </summary>
/// <seealso cref="CameraSettingsBase" />
public class CameraStillSettings : CameraSettingsBase {
private Int32 _rotate;
/// <inheritdoc />
public override String CommandName => "raspistill";
/// <summary> /// <summary>
/// Defines a wrapper for the raspistill program and its settings (command-line arguments). /// Gets or sets a value indicating whether the preview window (if enabled) uses native capture resolution
/// This may slow down preview FPS.
/// </summary> /// </summary>
/// <seealso cref="CameraSettingsBase" /> public Boolean CaptureDisplayPreviewAtResolution { get; set; } = false;
public class CameraStillSettings : CameraSettingsBase
{ /// <summary>
private int _rotate; /// Gets or sets the encoding format the hardware will use for the output.
/// </summary>
/// <inheritdoc /> public CameraImageEncodingFormat CaptureEncoding { get; set; } = CameraImageEncodingFormat.Jpg;
public override string CommandName => "raspistill";
/// <summary>
/// <summary> /// Gets or sets the quality for JPEG only encoding mode.
/// Gets or sets a value indicating whether the preview window (if enabled) uses native capture resolution /// Value ranges from 0 to 100.
/// This may slow down preview FPS. /// </summary>
/// </summary> public Int32 CaptureJpegQuality { get; set; } = 90;
public bool CaptureDisplayPreviewAtResolution { get; set; } = false;
/// <summary>
/// <summary> /// Gets or sets a value indicating whether the JPEG encoder should add raw bayer metadata.
/// Gets or sets the encoding format the hardware will use for the output. /// </summary>
/// </summary> public Boolean CaptureJpegIncludeRawBayerMetadata { get; set; } = false;
public CameraImageEncodingFormat CaptureEncoding { get; set; } = CameraImageEncodingFormat.Jpg;
/// <summary>
/// <summary> /// JPEG EXIF data
/// Gets or sets the quality for JPEG only encoding mode. /// Keys and values must be already properly escaped. Otherwise the command will fail.
/// Value ranges from 0 to 100. /// </summary>
/// </summary> public Dictionary<String, String> CaptureJpegExtendedInfo { get; } = new Dictionary<String, String>();
public int CaptureJpegQuality { get; set; } = 90;
/// <summary>
/// <summary> /// Gets or sets a value indicating whether [horizontal flip].
/// Gets or sets a value indicating whether the JPEG encoder should add raw bayer metadata. /// </summary>
/// </summary> /// <value>
public bool CaptureJpegIncludeRawBayerMetadata { get; set; } = false; /// <c>true</c> if [horizontal flip]; otherwise, <c>false</c>.
/// </value>
/// <summary> public Boolean HorizontalFlip { get; set; } = false;
/// JPEG EXIF data
/// Keys and values must be already properly escaped. Otherwise the command will fail. /// <summary>
/// </summary> /// Gets or sets a value indicating whether [vertical flip].
public Dictionary<string, string> CaptureJpegExtendedInfo { get; } = new Dictionary<string, string>(); /// </summary>
/// <value>
/// <summary> /// <c>true</c> if [vertical flip]; otherwise, <c>false</c>.
/// Gets or sets a value indicating whether [horizontal flip]. /// </value>
/// </summary> public Boolean VerticalFlip { get; set; } = false;
/// <value>
/// <c>true</c> if [horizontal flip]; otherwise, <c>false</c>. /// <summary>
/// </value> /// Gets or sets the rotation.
public bool HorizontalFlip { get; set; } = false; /// </summary>
/// <exception cref="ArgumentOutOfRangeException">Valid range 0-359.</exception>
/// <summary> public Int32 Rotation {
/// Gets or sets a value indicating whether [vertical flip]. get => this._rotate;
/// </summary> set {
/// <value> if(value < 0 || value > 359) {
/// <c>true</c> if [vertical flip]; otherwise, <c>false</c>. throw new ArgumentOutOfRangeException(nameof(value), "Valid range 0-359");
/// </value> }
public bool VerticalFlip { get; set; } = false;
this._rotate = value;
/// <summary> }
/// Gets or sets the rotation. }
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Valid range 0-359.</exception> /// <inheritdoc />
public int Rotation public override String CreateProcessArguments() {
{ StringBuilder sb = new StringBuilder(base.CreateProcessArguments());
get => _rotate; _ = sb.Append($" -e {this.CaptureEncoding.ToString().ToLowerInvariant()}");
set
{ // JPEG Encoder specific arguments
if (value < 0 || value > 359) if(this.CaptureEncoding == CameraImageEncodingFormat.Jpg) {
{ _ = sb.Append($" -q {this.CaptureJpegQuality.Clamp(0, 100).ToString(Ci)}");
throw new ArgumentOutOfRangeException(nameof(value), "Valid range 0-359");
} if(this.CaptureJpegIncludeRawBayerMetadata) {
_ = sb.Append(" -r");
_rotate = value; }
}
} // JPEG EXIF data
if(this.CaptureJpegExtendedInfo.Count > 0) {
/// <inheritdoc /> foreach(KeyValuePair<String, String> kvp in this.CaptureJpegExtendedInfo) {
public override string CreateProcessArguments() if(String.IsNullOrWhiteSpace(kvp.Key) || String.IsNullOrWhiteSpace(kvp.Value)) {
{ continue;
var sb = new StringBuilder(base.CreateProcessArguments()); }
sb.Append($" -e {CaptureEncoding.ToString().ToLowerInvariant()}");
_ = sb.Append($" -x \"{kvp.Key.Replace("\"", "'")}={kvp.Value.Replace("\"", "'")}\"");
// JPEG Encoder specific arguments }
if (CaptureEncoding == CameraImageEncodingFormat.Jpg) }
{ }
sb.Append($" -q {CaptureJpegQuality.Clamp(0, 100).ToString(Ci)}");
// Display preview settings
if (CaptureJpegIncludeRawBayerMetadata) if(this.CaptureDisplayPreview && this.CaptureDisplayPreviewAtResolution) {
sb.Append(" -r"); _ = sb.Append(" -fp");
}
// JPEG EXIF data
if (CaptureJpegExtendedInfo.Count > 0) if(this.Rotation != 0) {
{ _ = sb.Append($" -rot {this.Rotation}");
foreach (var kvp in CaptureJpegExtendedInfo) }
{
if (string.IsNullOrWhiteSpace(kvp.Key) || string.IsNullOrWhiteSpace(kvp.Value)) if(this.HorizontalFlip) {
continue; _ = sb.Append(" -hf");
}
sb.Append($" -x \"{kvp.Key.Replace("\"", "'")}={kvp.Value.Replace("\"", "'")}\"");
} if(this.VerticalFlip) {
} _ = sb.Append(" -vf");
} }
// Display preview settings return sb.ToString();
if (CaptureDisplayPreview && CaptureDisplayPreviewAtResolution) sb.Append(" -fp"); }
}
if (Rotation != 0) sb.Append($" -rot {Rotation}");
if (HorizontalFlip) sb.Append(" -hf");
if (VerticalFlip) sb.Append(" -vf");
return sb.ToString();
}
}
} }

View File

@ -1,104 +1,106 @@
namespace Unosquare.RaspberryIO.Camera using System;
{ using System.Text;
using System.Text;
namespace Unosquare.RaspberryIO.Camera {
/// <summary>
/// Represents the raspivid camera settings for video capture functionality.
/// </summary>
/// <seealso cref="CameraSettingsBase" />
public class CameraVideoSettings : CameraSettingsBase {
private Int32 _length;
/// <inheritdoc />
public override String CommandName => "raspivid";
/// <summary> /// <summary>
/// Represents the raspivid camera settings for video capture functionality. /// Use bits per second, so 10Mbits/s would be -b 10000000. For H264, 1080p30 a high quality bitrate would be 15Mbits/s or more.
/// Maximum bitrate is 25Mbits/s (-b 25000000), but much over 17Mbits/s won't show noticeable improvement at 1080p30.
/// Default -1.
/// </summary> /// </summary>
/// <seealso cref="CameraSettingsBase" /> public Int32 CaptureBitrate { get; set; } = -1;
public class CameraVideoSettings : CameraSettingsBase
{ /// <summary>
private int _length; /// Gets or sets the framerate.
/// Default 25, range 2 to 30.
/// <inheritdoc /> /// </summary>
public override string CommandName => "raspivid"; public Int32 CaptureFramerate { get; set; } = 25;
/// <summary> /// <summary>
/// Use bits per second, so 10Mbits/s would be -b 10000000. For H264, 1080p30 a high quality bitrate would be 15Mbits/s or more. /// Sets the intra refresh period (GoP) rate for the recorded video. H264 video uses a complete frame (I-frame) every intra
/// Maximum bitrate is 25Mbits/s (-b 25000000), but much over 17Mbits/s won't show noticeable improvement at 1080p30. /// refresh period, from which subsequent frames are based. This option specifies the number of frames between each I-frame.
/// Default -1. /// Larger numbers here will reduce the size of the resulting video, and smaller numbers make the stream less error-prone.
/// </summary> /// </summary>
public int CaptureBitrate { get; set; } = -1; public Int32 CaptureKeyframeRate { get; set; } = 25;
/// <summary> /// <summary>
/// Gets or sets the framerate. /// Sets the initial quantisation parameter for the stream. Varies from approximately 10 to 40, and will greatly affect
/// Default 25, range 2 to 30. /// the quality of the recording. Higher values reduce quality and decrease file size. Combine this setting with a
/// </summary> /// bitrate of 0 to set a completely variable bitrate.
public int CaptureFramerate { get; set; } = 25; /// </summary>
public Int32 CaptureQuantisation { get; set; } = 23;
/// <summary>
/// Sets the intra refresh period (GoP) rate for the recorded video. H264 video uses a complete frame (I-frame) every intra /// <summary>
/// refresh period, from which subsequent frames are based. This option specifies the number of frames between each I-frame. /// Gets or sets the profile.
/// Larger numbers here will reduce the size of the resulting video, and smaller numbers make the stream less error-prone. /// Sets the H264 profile to be used for the encoding.
/// </summary> /// Default is Main mode.
public int CaptureKeyframeRate { get; set; } = 25; /// </summary>
public CameraH264Profile CaptureProfile { get; set; } = CameraH264Profile.Main;
/// <summary>
/// Sets the initial quantisation parameter for the stream. Varies from approximately 10 to 40, and will greatly affect /// <summary>
/// the quality of the recording. Higher values reduce quality and decrease file size. Combine this setting with a /// Forces the stream to include PPS and SPS headers on every I-frame. Needed for certain streaming cases
/// bitrate of 0 to set a completely variable bitrate. /// e.g. Apple HLS. These headers are small, so don't greatly increase the file size.
/// </summary> /// </summary>
public int CaptureQuantisation { get; set; } = 23; /// <value>
/// <c>true</c> if [interleave headers]; otherwise, <c>false</c>.
/// <summary> /// </value>
/// Gets or sets the profile. public Boolean CaptureInterleaveHeaders { get; set; } = true;
/// Sets the H264 profile to be used for the encoding.
/// Default is Main mode. /// <summary>
/// </summary> /// Toggle fullscreen mode for video preview.
public CameraH264Profile CaptureProfile { get; set; } = CameraH264Profile.Main; /// </summary>
public Boolean Fullscreen { get; set; } = false;
/// <summary>
/// Forces the stream to include PPS and SPS headers on every I-frame. Needed for certain streaming cases /// <summary>
/// e.g. Apple HLS. These headers are small, so don't greatly increase the file size. /// Specifies the path to save video files.
/// </summary> /// </summary>
/// <value> public String? VideoFileName {
/// <c>true</c> if [interleave headers]; otherwise, <c>false</c>. get; set;
/// </value> }
public bool CaptureInterleaveHeaders { get; set; } = true;
/// <summary>
/// <summary> /// Video stream length in seconds.
/// Toggle fullscreen mode for video preview. /// </summary>
/// </summary> public Int32 LengthInSeconds {
public bool Fullscreen { get; set; } = false; get => this._length;
set => this._length = value * 1000;
/// <summary> }
/// Specifies the path to save video files.
/// </summary> /// <summary>
public string VideoFileName { get; set; } /// Switch on an option to display the preview after compression. This will show any compression artefacts in the preview window. In normal operation,
/// the preview will show the camera output prior to being compressed. This option is not guaranteed to work in future releases.
/// <summary> /// </summary>
/// Video stream length in seconds. /// <value>
/// </summary> /// <c>true</c> if [capture display preview encoded]; otherwise, <c>false</c>.
public int LengthInSeconds /// </value>
{ public Boolean CaptureDisplayPreviewEncoded { get; set; } = false;
get => _length;
set => _length = value * 1000; /// <inheritdoc />
} public override String CreateProcessArguments() {
StringBuilder sb = new StringBuilder(base.CreateProcessArguments());
/// <summary>
/// Switch on an option to display the preview after compression. This will show any compression artefacts in the preview window. In normal operation, if(this.Fullscreen) {
/// the preview will show the camera output prior to being compressed. This option is not guaranteed to work in future releases. _ = sb.Append(" -f");
/// </summary> }
/// <value>
/// <c>true</c> if [capture display preview encoded]; otherwise, <c>false</c>. if(this.LengthInSeconds != 0) {
/// </value> _ = sb.Append($" -t {this.LengthInSeconds}");
public bool CaptureDisplayPreviewEncoded { get; set; } = false; }
/// <inheritdoc /> if(!String.IsNullOrEmpty(this.VideoFileName)) {
public override string CreateProcessArguments() _ = sb.Append($" -o {this.VideoFileName}");
{ }
var sb = new StringBuilder(base.CreateProcessArguments());
return sb.ToString();
if (Fullscreen) }
sb.Append(" -f"); }
if (LengthInSeconds != 0)
sb.Append($" -t {LengthInSeconds}");
if (!string.IsNullOrEmpty(VideoFileName))
sb.Append($" -o {VideoFileName}");
return sb.ToString();
}
}
} }

View File

@ -1,423 +1,413 @@
namespace Unosquare.RaspberryIO.Camera namespace Unosquare.RaspberryIO.Camera {
{ using System;
using System;
/// <summary>
/// Defines the available encoding formats for the Raspberry Pi camera module.
/// </summary>
public enum CameraImageEncodingFormat {
/// <summary> /// <summary>
/// Defines the available encoding formats for the Raspberry Pi camera module. /// The JPG
/// </summary> /// </summary>
public enum CameraImageEncodingFormat Jpg,
{
/// <summary>
/// The JPG
/// </summary>
Jpg,
/// <summary>
/// The BMP
/// </summary>
Bmp,
/// <summary>
/// The GIF
/// </summary>
Gif,
/// <summary>
/// The PNG
/// </summary>
Png
}
/// <summary> /// <summary>
/// Defines the different exposure modes for the Raspberry Pi's camera module. /// The BMP
/// </summary> /// </summary>
public enum CameraExposureMode Bmp,
{
/// <summary>
/// The automatic
/// </summary>
Auto,
/// <summary>
/// The night
/// </summary>
Night,
/// <summary>
/// The night preview
/// </summary>
NightPreview,
/// <summary>
/// The backlight
/// </summary>
Backlight,
/// <summary>
/// The spotlight
/// </summary>
Spotlight,
/// <summary>
/// The sports
/// </summary>
Sports,
/// <summary>
/// The snow
/// </summary>
Snow,
/// <summary>
/// The beach
/// </summary>
Beach,
/// <summary>
/// The very long
/// </summary>
VeryLong,
/// <summary>
/// The fixed FPS
/// </summary>
FixedFps,
/// <summary>
/// The anti shake
/// </summary>
AntiShake,
/// <summary>
/// The fireworks
/// </summary>
Fireworks
}
/// <summary> /// <summary>
/// Defines the different AWB (Auto White Balance) modes for the Raspberry Pi's camera module. /// The GIF
/// </summary> /// </summary>
public enum CameraWhiteBalanceMode Gif,
{
/// <summary>
/// No white balance
/// </summary>
Off,
/// <summary>
/// The automatic
/// </summary>
Auto,
/// <summary>
/// The sun
/// </summary>
Sun,
/// <summary>
/// The cloud
/// </summary>
Cloud,
/// <summary>
/// The shade
/// </summary>
Shade,
/// <summary>
/// The tungsten
/// </summary>
Tungsten,
/// <summary>
/// The fluorescent
/// </summary>
Fluorescent,
/// <summary>
/// The incandescent
/// </summary>
Incandescent,
/// <summary>
/// The flash
/// </summary>
Flash,
/// <summary>
/// The horizon
/// </summary>
Horizon
}
/// <summary> /// <summary>
/// Defines the available image effects for the Raspberry Pi's camera module. /// The PNG
/// </summary> /// </summary>
public enum CameraImageEffect Png
{ }
/// <summary>
/// No effect /// <summary>
/// </summary> /// Defines the different exposure modes for the Raspberry Pi's camera module.
None, /// </summary>
public enum CameraExposureMode {
/// <summary>
/// The negative
/// </summary>
Negative,
/// <summary>
/// The solarise
/// </summary>
Solarise,
/// <summary>
/// The whiteboard
/// </summary>
Whiteboard,
/// <summary>
/// The blackboard
/// </summary>
Blackboard,
/// <summary>
/// The sketch
/// </summary>
Sketch,
/// <summary>
/// The denoise
/// </summary>
Denoise,
/// <summary>
/// The emboss
/// </summary>
Emboss,
/// <summary>
/// The oil paint
/// </summary>
OilPaint,
/// <summary>
/// The hatch
/// </summary>
Hatch,
/// <summary>
/// Graphite Pen
/// </summary>
GPen,
/// <summary>
/// The pastel
/// </summary>
Pastel,
/// <summary>
/// The water colour
/// </summary>
WaterColour,
/// <summary>
/// The film
/// </summary>
Film,
/// <summary>
/// The blur
/// </summary>
Blur,
/// <summary>
/// The saturation
/// </summary>
Saturation,
/// <summary>
/// The solour swap
/// </summary>
SolourSwap,
/// <summary>
/// The washed out
/// </summary>
WashedOut,
/// <summary>
/// The colour point
/// </summary>
ColourPoint,
/// <summary>
/// The colour balance
/// </summary>
ColourBalance,
/// <summary>
/// The cartoon
/// </summary>
Cartoon
}
/// <summary> /// <summary>
/// Defines the different metering modes for the Raspberry Pi's camera module. /// The automatic
/// </summary> /// </summary>
public enum CameraMeteringMode Auto,
{
/// <summary>
/// The average
/// </summary>
Average,
/// <summary>
/// The spot
/// </summary>
Spot,
/// <summary>
/// The backlit
/// </summary>
Backlit,
/// <summary>
/// The matrix
/// </summary>
Matrix
}
/// <summary> /// <summary>
/// Defines the different image rotation modes for the Raspberry Pi's camera module. /// The night
/// </summary> /// </summary>
public enum CameraImageRotation Night,
{
/// <summary>
/// No rerotation
/// </summary>
None = 0,
/// <summary>
/// 90 Degrees
/// </summary>
Degrees90 = 90,
/// <summary>
/// 180 Degrees
/// </summary>
Degrees180 = 180,
/// <summary>
/// 270 degrees
/// </summary>
Degrees270 = 270
}
/// <summary> /// <summary>
/// Defines the different DRC (Dynamic Range Compensation) modes for the Raspberry Pi's camera module /// The night preview
/// Helpful for low light photos.
/// </summary> /// </summary>
public enum CameraDynamicRangeCompensation NightPreview,
{
/// <summary>
/// The off setting
/// </summary>
Off,
/// <summary>
/// The low
/// </summary>
Low,
/// <summary>
/// The medium
/// </summary>
Medium,
/// <summary>
/// The high
/// </summary>
High
}
/// <summary> /// <summary>
/// Defines the bit-wise mask flags for the available annotation elements for the Raspberry Pi's camera module. /// The backlight
/// </summary> /// </summary>
[Flags] Backlight,
public enum CameraAnnotation
{
/// <summary>
/// The none
/// </summary>
None = 0,
/// <summary>
/// The time
/// </summary>
Time = 4,
/// <summary>
/// The date
/// </summary>
Date = 8,
/// <summary>
/// The shutter settings
/// </summary>
ShutterSettings = 16,
/// <summary>
/// The caf settings
/// </summary>
CafSettings = 32,
/// <summary>
/// The gain settings
/// </summary>
GainSettings = 64,
/// <summary>
/// The lens settings
/// </summary>
LensSettings = 128,
/// <summary>
/// The motion settings
/// </summary>
MotionSettings = 256,
/// <summary>
/// The frame number
/// </summary>
FrameNumber = 512,
/// <summary>
/// The solid background
/// </summary>
SolidBackground = 1024
}
/// <summary> /// <summary>
/// Defines the different H.264 encoding profiles to be used when capturing video. /// The spotlight
/// </summary> /// </summary>
public enum CameraH264Profile Spotlight,
{
/// <summary> /// <summary>
/// BP: Primarily for lower-cost applications with limited computing resources, /// The sports
/// this profile is used widely in videoconferencing and mobile applications. /// </summary>
/// </summary> Sports,
Baseline,
/// <summary>
/// <summary> /// The snow
/// MP: Originally intended as the mainstream consumer profile for broadcast /// </summary>
/// and storage applications, the importance of this profile faded when the High profile was developed for those applications. Snow,
/// </summary>
Main, /// <summary>
/// The beach
/// <summary> /// </summary>
/// HiP: The primary profile for broadcast and disc storage applications, particularly Beach,
/// for high-definition television applications (this is the profile adopted into HD DVD and Blu-ray Disc, for example).
/// </summary> /// <summary>
High /// The very long
} /// </summary>
VeryLong,
/// <summary>
/// The fixed FPS
/// </summary>
FixedFps,
/// <summary>
/// The anti shake
/// </summary>
AntiShake,
/// <summary>
/// The fireworks
/// </summary>
Fireworks
}
/// <summary>
/// Defines the different AWB (Auto White Balance) modes for the Raspberry Pi's camera module.
/// </summary>
public enum CameraWhiteBalanceMode {
/// <summary>
/// No white balance
/// </summary>
Off,
/// <summary>
/// The automatic
/// </summary>
Auto,
/// <summary>
/// The sun
/// </summary>
Sun,
/// <summary>
/// The cloud
/// </summary>
Cloud,
/// <summary>
/// The shade
/// </summary>
Shade,
/// <summary>
/// The tungsten
/// </summary>
Tungsten,
/// <summary>
/// The fluorescent
/// </summary>
Fluorescent,
/// <summary>
/// The incandescent
/// </summary>
Incandescent,
/// <summary>
/// The flash
/// </summary>
Flash,
/// <summary>
/// The horizon
/// </summary>
Horizon
}
/// <summary>
/// Defines the available image effects for the Raspberry Pi's camera module.
/// </summary>
public enum CameraImageEffect {
/// <summary>
/// No effect
/// </summary>
None,
/// <summary>
/// The negative
/// </summary>
Negative,
/// <summary>
/// The solarise
/// </summary>
Solarise,
/// <summary>
/// The whiteboard
/// </summary>
Whiteboard,
/// <summary>
/// The blackboard
/// </summary>
Blackboard,
/// <summary>
/// The sketch
/// </summary>
Sketch,
/// <summary>
/// The denoise
/// </summary>
Denoise,
/// <summary>
/// The emboss
/// </summary>
Emboss,
/// <summary>
/// The oil paint
/// </summary>
OilPaint,
/// <summary>
/// The hatch
/// </summary>
Hatch,
/// <summary>
/// Graphite Pen
/// </summary>
GPen,
/// <summary>
/// The pastel
/// </summary>
Pastel,
/// <summary>
/// The water colour
/// </summary>
WaterColour,
/// <summary>
/// The film
/// </summary>
Film,
/// <summary>
/// The blur
/// </summary>
Blur,
/// <summary>
/// The saturation
/// </summary>
Saturation,
/// <summary>
/// The solour swap
/// </summary>
SolourSwap,
/// <summary>
/// The washed out
/// </summary>
WashedOut,
/// <summary>
/// The colour point
/// </summary>
ColourPoint,
/// <summary>
/// The colour balance
/// </summary>
ColourBalance,
/// <summary>
/// The cartoon
/// </summary>
Cartoon
}
/// <summary>
/// Defines the different metering modes for the Raspberry Pi's camera module.
/// </summary>
public enum CameraMeteringMode {
/// <summary>
/// The average
/// </summary>
Average,
/// <summary>
/// The spot
/// </summary>
Spot,
/// <summary>
/// The backlit
/// </summary>
Backlit,
/// <summary>
/// The matrix
/// </summary>
Matrix
}
/// <summary>
/// Defines the different image rotation modes for the Raspberry Pi's camera module.
/// </summary>
public enum CameraImageRotation {
/// <summary>
/// No rerotation
/// </summary>
None = 0,
/// <summary>
/// 90 Degrees
/// </summary>
Degrees90 = 90,
/// <summary>
/// 180 Degrees
/// </summary>
Degrees180 = 180,
/// <summary>
/// 270 degrees
/// </summary>
Degrees270 = 270
}
/// <summary>
/// Defines the different DRC (Dynamic Range Compensation) modes for the Raspberry Pi's camera module
/// Helpful for low light photos.
/// </summary>
public enum CameraDynamicRangeCompensation {
/// <summary>
/// The off setting
/// </summary>
Off,
/// <summary>
/// The low
/// </summary>
Low,
/// <summary>
/// The medium
/// </summary>
Medium,
/// <summary>
/// The high
/// </summary>
High
}
/// <summary>
/// Defines the bit-wise mask flags for the available annotation elements for the Raspberry Pi's camera module.
/// </summary>
[Flags]
public enum CameraAnnotation {
/// <summary>
/// The none
/// </summary>
None = 0,
/// <summary>
/// The time
/// </summary>
Time = 4,
/// <summary>
/// The date
/// </summary>
Date = 8,
/// <summary>
/// The shutter settings
/// </summary>
ShutterSettings = 16,
/// <summary>
/// The caf settings
/// </summary>
CafSettings = 32,
/// <summary>
/// The gain settings
/// </summary>
GainSettings = 64,
/// <summary>
/// The lens settings
/// </summary>
LensSettings = 128,
/// <summary>
/// The motion settings
/// </summary>
MotionSettings = 256,
/// <summary>
/// The frame number
/// </summary>
FrameNumber = 512,
/// <summary>
/// The solid background
/// </summary>
SolidBackground = 1024
}
/// <summary>
/// Defines the different H.264 encoding profiles to be used when capturing video.
/// </summary>
public enum CameraH264Profile {
/// <summary>
/// BP: Primarily for lower-cost applications with limited computing resources,
/// this profile is used widely in videoconferencing and mobile applications.
/// </summary>
Baseline,
/// <summary>
/// MP: Originally intended as the mainstream consumer profile for broadcast
/// and storage applications, the importance of this profile faded when the High profile was developed for those applications.
/// </summary>
Main,
/// <summary>
/// HiP: The primary profile for broadcast and disc storage applications, particularly
/// for high-definition television applications (this is the profile adopted into HD DVD and Blu-ray Disc, for example).
/// </summary>
High
}
} }

View File

@ -1,113 +1,104 @@
namespace Unosquare.RaspberryIO.Computer using System;
{ using System.Linq;
using Swan; using System.Threading.Tasks;
using System;
using System.Linq; using Swan;
using System.Threading.Tasks;
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// Settings for audio device.
/// </summary>
public class AudioSettings : SingletonBase<AudioSettings> {
private const String DefaultControlName = "PCM";
private const Int32 DefaultCardNumber = 0;
private readonly String[] _errorMess = { "Invalid", "Unable" };
/// <summary> /// <summary>
/// Settings for audio device. /// Gets the current audio state.
/// </summary> /// </summary>
public class AudioSettings : SingletonBase<AudioSettings> /// <param name="cardNumber">The card number.</param>
{ /// <param name="controlName">Name of the control.</param>
private const string DefaultControlName = "PCM"; /// <returns>An <see cref="AudioState"/> object.</returns>
private const int DefaultCardNumber = 0; /// <exception cref="InvalidOperationException">Invalid command, card number or control name.</exception>
public async Task<AudioState> GetState(Int32 cardNumber = DefaultCardNumber, String controlName = DefaultControlName) {
private readonly string[] _errorMess = { "Invalid", "Unable" }; String volumeInfo = await ProcessRunner.GetProcessOutputAsync("amixer", $"-c {cardNumber} get {controlName}").ConfigureAwait(false);
/// <summary> String[] lines = volumeInfo.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
/// Gets the current audio state.
/// </summary> if(!lines.Any()) {
/// <param name="cardNumber">The card number.</param> throw new InvalidOperationException("Invalid command.");
/// <param name="controlName">Name of the control.</param> }
/// <returns>An <see cref="AudioState"/> object.</returns>
/// <exception cref="InvalidOperationException">Invalid command, card number or control name.</exception> if(this._errorMess.Any(x => lines[0].Contains(x))) {
public async Task<AudioState> GetState(int cardNumber = DefaultCardNumber, string controlName = DefaultControlName) throw new InvalidOperationException(lines[0]);
{ }
var volumeInfo = await ProcessRunner.GetProcessOutputAsync("amixer", $"-c {cardNumber} get {controlName}").ConfigureAwait(false);
String volumeLine = lines.FirstOrDefault(x => x.Trim().StartsWith("Mono:", StringComparison.OrdinalIgnoreCase));
var lines = volumeInfo.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if(volumeLine == null) {
if (!lines.Any()) throw new InvalidOperationException("Unexpected output from 'amixer'.");
throw new InvalidOperationException("Invalid command."); }
if (_errorMess.Any(x => lines[0].Contains(x))) String[] sections = volumeLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
throw new InvalidOperationException(lines[0]);
Int32 level = Int32.Parse(sections[3][1..^2], System.Globalization.NumberFormatInfo.InvariantInfo);
var volumeLine = lines
.FirstOrDefault(x => x.Trim() Single decibels = Single.Parse(sections[4][1..^3], System.Globalization.NumberFormatInfo.InvariantInfo);
.StartsWith("Mono:", StringComparison.OrdinalIgnoreCase));
Boolean isMute = sections[5].Equals("[off]", StringComparison.CurrentCultureIgnoreCase);
if (volumeLine == null)
throw new InvalidOperationException("Unexpected output from 'amixer'."); return new AudioState(cardNumber, controlName, level, decibels, isMute);
}
var sections = volumeLine.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries); /// <summary>
/// Sets the volume percentage.
var level = int.Parse(sections[3].Substring(1, sections[3].Length - 3), /// </summary>
System.Globalization.NumberFormatInfo.InvariantInfo); /// <param name="level">The percentage level.</param>
/// <param name="cardNumber">The card number.</param>
var decibels = float.Parse(sections[4].Substring(1, sections[4].Length - 4), /// <param name="controlName">Name of the control.</param>
System.Globalization.NumberFormatInfo.InvariantInfo); /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
/// <exception cref="InvalidOperationException">Invalid card number or control name.</exception>
var isMute = sections[5].Equals("[off]", public Task SetVolumePercentage(Int32 level, Int32 cardNumber = DefaultCardNumber, String controlName = DefaultControlName) => SetAudioCommand($"{level}%", cardNumber, controlName);
StringComparison.CurrentCultureIgnoreCase);
/// <summary>
return new AudioState(cardNumber, controlName, level, decibels, isMute); /// Sets the volume by decibels.
} /// </summary>
/// <param name="decibels">The decibels.</param>
/// <summary> /// <param name="cardNumber">The card number.</param>
/// Sets the volume percentage. /// <param name="controlName">Name of the control.</param>
/// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
/// <param name="level">The percentage level.</param> /// <exception cref="InvalidOperationException">Invalid card number or control name.</exception>
/// <param name="cardNumber">The card number.</param> public Task SetVolumeByDecibels(Single decibels, Int32 cardNumber = DefaultCardNumber, String controlName = DefaultControlName) => SetAudioCommand($"{decibels}dB", cardNumber, controlName);
/// <param name="controlName">Name of the control.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> /// <summary>
/// <exception cref="InvalidOperationException">Invalid card number or control name.</exception> /// Increments the volume by decibels.
public Task SetVolumePercentage(int level, int cardNumber = DefaultCardNumber, string controlName = DefaultControlName) => /// </summary>
SetAudioCommand($"{level}%", cardNumber, controlName); /// <param name="decibels">The decibels to increment or decrement.</param>
/// <param name="cardNumber">The card number.</param>
/// <summary> /// <param name="controlName">Name of the control.</param>
/// Sets the volume by decibels. /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
/// </summary> /// <exception cref="InvalidOperationException">Invalid card number or control name.</exception>
/// <param name="decibels">The decibels.</param> public Task IncrementVolume(Single decibels, Int32 cardNumber = DefaultCardNumber, String controlName = DefaultControlName) => SetAudioCommand($"{decibels}dB{(decibels < 0 ? "-" : "+")}", cardNumber, controlName);
/// <param name="cardNumber">The card number.</param>
/// <param name="controlName">Name of the control.</param> /// <summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> /// Toggles the mute state.
/// <exception cref="InvalidOperationException">Invalid card number or control name.</exception> /// </summary>
public Task SetVolumeByDecibels(float decibels, int cardNumber = DefaultCardNumber, string controlName = DefaultControlName) => /// <param name="mute">if set to <c>true</c>, mutes the audio.</param>
SetAudioCommand($"{decibels}dB", cardNumber, controlName); /// <param name="cardNumber">The card number.</param>
/// <param name="controlName">Name of the control.</param>
/// <summary> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
/// Increments the volume by decibels. /// <exception cref="InvalidOperationException">Invalid card number or control name.</exception>
/// </summary> public Task ToggleMute(Boolean mute, Int32 cardNumber = DefaultCardNumber, String controlName = DefaultControlName) => SetAudioCommand(mute ? "mute" : "unmute", cardNumber, controlName);
/// <param name="decibels">The decibels to increment or decrement.</param>
/// <param name="cardNumber">The card number.</param> private static async Task<String> SetAudioCommand(String command, Int32 cardNumber = DefaultCardNumber, String controlName = DefaultControlName) {
/// <param name="controlName">Name of the control.</param> String taskResult = await ProcessRunner.GetProcessOutputAsync("amixer", $"-q -c {cardNumber} -- set {controlName} {command}").ConfigureAwait(false);
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
/// <exception cref="InvalidOperationException">Invalid card number or control name.</exception> if(!String.IsNullOrWhiteSpace(taskResult)) {
public Task IncrementVolume(float decibels, int cardNumber = DefaultCardNumber, string controlName = DefaultControlName) => throw new InvalidOperationException(taskResult.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).First());
SetAudioCommand($"{decibels}dB{(decibels < 0 ? "-" : "+")}", cardNumber, controlName); }
/// <summary> return taskResult;
/// Toggles the mute state. }
/// </summary> }
/// <param name="mute">if set to <c>true</c>, mutes the audio.</param>
/// <param name="cardNumber">The card number.</param>
/// <param name="controlName">Name of the control.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
/// <exception cref="InvalidOperationException">Invalid card number or control name.</exception>
public Task ToggleMute(bool mute, int cardNumber = DefaultCardNumber, string controlName = DefaultControlName) =>
SetAudioCommand(mute ? "mute" : "unmute", cardNumber, controlName);
private static async Task<string> SetAudioCommand(string command, int cardNumber = DefaultCardNumber, string controlName = DefaultControlName)
{
var taskResult = await ProcessRunner.GetProcessOutputAsync("amixer", $"-q -c {cardNumber} -- set {controlName} {command}").ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(taskResult))
throw new InvalidOperationException(taskResult.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).First());
return taskResult;
}
}
} }

View File

@ -1,64 +1,72 @@
namespace Unosquare.RaspberryIO.Computer using System;
{
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// Manage the volume of any sound device.
/// </summary>
public readonly struct AudioState {
/// <summary> /// <summary>
/// Manage the volume of any sound device. /// Initializes a new instance of the <see cref="AudioState"/> struct.
/// </summary> /// </summary>
public readonly struct AudioState /// <param name="cardNumber">The card number.</param>
{ /// <param name="controlName">Name of the control.</param>
/// <summary> /// <param name="level">The volume level in percentaje.</param>
/// Initializes a new instance of the <see cref="AudioState"/> struct. /// <param name="decibels">The volume level in decibels.</param>
/// </summary> /// <param name="isMute">if set to <c>true</c> the audio is mute.</param>
/// <param name="cardNumber">The card number.</param> public AudioState(Int32 cardNumber, String controlName, Int32 level, Single decibels, Boolean isMute) {
/// <param name="controlName">Name of the control.</param> this.CardNumber = cardNumber;
/// <param name="level">The volume level in percentaje.</param> this.ControlName = controlName;
/// <param name="decibels">The volume level in decibels.</param> this.Level = level;
/// <param name="isMute">if set to <c>true</c> the audio is mute.</param> this.Decibels = decibels;
public AudioState(int cardNumber, string controlName, int level, float decibels, bool isMute) this.IsMute = isMute;
{ }
CardNumber = cardNumber;
ControlName = controlName; /// <summary>
Level = level; /// Gets the card number.
Decibels = decibels; /// </summary>
IsMute = isMute; public Int32 CardNumber {
} get;
}
/// <summary>
/// Gets the card number. /// <summary>
/// </summary> /// Gets the name of the current control.
public int CardNumber { get; } /// </summary>
public String ControlName {
/// <summary> get;
/// Gets the name of the current control. }
/// </summary>
public string ControlName { get; } /// <summary>
/// Gets the volume level in percentage.
/// <summary> /// </summary>
/// Gets the volume level in percentage. public Int32 Level {
/// </summary> get;
public int Level { get; } }
/// <summary> /// <summary>
/// Gets the volume level in decibels. /// Gets the volume level in decibels.
/// </summary> /// </summary>
public float Decibels { get; } public Single Decibels {
get;
/// <summary> }
/// Gets a value indicating whether the audio is mute.
/// </summary> /// <summary>
public bool IsMute { get; } /// Gets a value indicating whether the audio is mute.
/// </summary>
/// <summary> public Boolean IsMute {
/// Returns a <see cref="string" /> that represents the audio state. get;
/// </summary> }
/// <returns>
/// A <see cref="string" /> that represents the audio state. /// <summary>
/// </returns> /// Returns a <see cref="String" /> that represents the audio state.
public override string ToString() => /// </summary>
"Device information: \n" + /// <returns>
$">> Name: {ControlName}\n" + /// A <see cref="String" /> that represents the audio state.
$">> Card number: {CardNumber}\n" + /// </returns>
$">> Volume (%): {Level}%\n" + public override String ToString() => "Device information: \n" +
$">> Volume (dB): {Decibels:0.00}dB\n" + $">> Name: {this.ControlName}\n" +
$">> Mute: [{(IsMute ? "Off" : "On")}]\n\n"; $">> Card number: {this.CardNumber}\n" +
} $">> Volume (%): {this.Level}%\n" +
$">> Volume (dB): {this.Decibels:0.00}dB\n" +
$">> Mute: [{(this.IsMute ? "Off" : "On")}]\n\n";
}
} }

View File

@ -1,271 +1,201 @@
namespace Unosquare.RaspberryIO.Computer using System;
{ using System.Collections.Generic;
using System; using System.Linq;
using System.Collections.Generic; using System.Threading;
using System.Linq; using System.Threading.Tasks;
using System.Threading;
using System.Threading.Tasks; using Swan;
using Swan;
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// Represents the Bluetooth information.
/// </summary>
public class Bluetooth : SingletonBase<Bluetooth> {
private const String BcCommand = "bluetoothctl";
/// <summary> /// <summary>
/// Represents the Bluetooth information. /// Turns on the Bluetooth adapter.
/// </summary> /// </summary>
public class Bluetooth : SingletonBase<Bluetooth> /// <param name="cancellationToken">The cancellation token.</param>
{ /// <returns>
private const string BcCommand = "bluetoothctl"; /// Returns true or false depending if the controller was turned on.
/// </returns>
/// <summary> /// <exception cref="BluetoothErrorException">Failed to power on:.</exception>
/// Turns on the Bluetooth adapter. public async Task<Boolean> PowerOn(CancellationToken cancellationToken = default) {
/// </summary> try {
/// <param name="cancellationToken">The cancellation token.</param> String output = await ProcessRunner.GetProcessOutputAsync(BcCommand, "power on", null, cancellationToken).ConfigureAwait(false);
/// <returns> return output.Contains("succeeded");
/// Returns true or false depending if the controller was turned on. } catch(Exception ex) {
/// </returns> throw new BluetoothErrorException($"Failed to power on: {ex.Message}");
/// <exception cref="BluetoothErrorException">Failed to power on:.</exception> }
public async Task<bool> PowerOn(CancellationToken cancellationToken = default) }
{
try /// <summary>
{ /// Turns off the bluetooth adapter.
var output = await ProcessRunner.GetProcessOutputAsync(BcCommand, "power on", null, cancellationToken) /// </summary>
.ConfigureAwait(false); /// <param name="cancellationToken">The cancellation token.</param>
return output.Contains("succeeded"); /// <returns>
} /// Returns true or false depending if the controller was turned off.
catch (Exception ex) /// </returns>
{ /// <exception cref="BluetoothErrorException">Failed to power off:.</exception>
throw new BluetoothErrorException($"Failed to power on: {ex.Message}"); public async Task<Boolean> PowerOff(CancellationToken cancellationToken = default) {
} try {
} String output = await ProcessRunner.GetProcessOutputAsync(BcCommand, "power off", null, cancellationToken).ConfigureAwait(false);
return output.Contains("succeeded");
/// <summary> } catch(Exception ex) {
/// Turns off the bluetooth adapter. throw new BluetoothErrorException($"Failed to power off: {ex.Message}");
/// </summary> }
/// <param name="cancellationToken">The cancellation token.</param> }
/// <returns>
/// Returns true or false depending if the controller was turned off. /// <summary>
/// </returns> /// Gets the list of detected devices.
/// <exception cref="BluetoothErrorException">Failed to power off:.</exception> /// </summary>
public async Task<bool> PowerOff(CancellationToken cancellationToken = default) /// <param name="cancellationToken">The cancellation token.</param>
{ /// <returns>
try /// Returns the list of detected devices.
{ /// </returns>
var output = await ProcessRunner.GetProcessOutputAsync(BcCommand, "power off", null, cancellationToken) /// <exception cref="BluetoothErrorException">Failed to retrieve devices:.</exception>
.ConfigureAwait(false); public async Task<IEnumerable<String>> ListDevices(CancellationToken cancellationToken = default) {
return output.Contains("succeeded"); try {
} using CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(3000);
catch (Exception ex) _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "scan on", null, cancellationTokenSource.Token).ConfigureAwait(false);
{ _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "scan off", null, cancellationToken).ConfigureAwait(false);
throw new BluetoothErrorException($"Failed to power off: {ex.Message}"); String devices = await ProcessRunner.GetProcessOutputAsync(BcCommand, "devices", null, cancellationToken).ConfigureAwait(false);
} return devices.Trim().Split('\n').Select(x => x.Trim());
} } catch(Exception ex) {
throw new BluetoothErrorException($"Failed to retrieve devices: {ex.Message}");
/// <summary> }
/// Gets the list of detected devices. }
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param> /// <summary>
/// <returns> /// Gets the list of bluetooth controllers.
/// Returns the list of detected devices. /// </summary>
/// </returns> /// <param name="cancellationToken">The cancellation token.</param>
/// <exception cref="BluetoothErrorException">Failed to retrieve devices:.</exception> /// <returns>
public async Task<IEnumerable<string>> ListDevices(CancellationToken cancellationToken = default) /// Returns the list of bluetooth controllers.
{ /// </returns>
try /// <exception cref="BluetoothErrorException">Failed to retrieve controllers:.</exception>
{ public async Task<IEnumerable<String>> ListControllers(CancellationToken cancellationToken = default) {
using var cancellationTokenSource = new CancellationTokenSource(3000); try {
await ProcessRunner.GetProcessOutputAsync(BcCommand, "scan on", null, cancellationTokenSource.Token) String controllers = await ProcessRunner.GetProcessOutputAsync(BcCommand, "list", null, cancellationToken).ConfigureAwait(false);
.ConfigureAwait(false); return controllers.Trim().Split('\n').Select(x => x.Trim());
await ProcessRunner.GetProcessOutputAsync(BcCommand, "scan off", null, cancellationToken) } catch(Exception ex) {
.ConfigureAwait(false); throw new BluetoothErrorException($"Failed to retrieve controllers: {ex.Message}");
var devices = await ProcessRunner.GetProcessOutputAsync(BcCommand, "devices", null, cancellationToken) }
.ConfigureAwait(false); }
return devices.Trim().Split('\n').Select(x => x.Trim());
} /// <summary>
catch (Exception ex) /// Pairs a specific device with a specific controller.
{ /// </summary>
throw new BluetoothErrorException($"Failed to retrieve devices: {ex.Message}"); /// <param name="controllerAddress">The mac address of the controller that will be used to pair.</param>
} /// <param name="deviceAddress">The mac address of the device that will be paired.</param>
} /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// <summary> /// Returns true or false if the pair was successfully.
/// Gets the list of bluetooth controllers. /// </returns>
/// </summary> /// <exception cref="BluetoothErrorException">Failed to Pair:.</exception>
/// <param name="cancellationToken">The cancellation token.</param> public async Task<Boolean> Pair(String controllerAddress, String deviceAddress, CancellationToken cancellationToken = default) {
/// <returns> try {
/// Returns the list of bluetooth controllers. // Selects the controller to pair. Once you select the controller, all controller-related commands will apply to it for three minutes.
/// </returns> _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, $"select {controllerAddress}", null, cancellationToken).ConfigureAwait(false);
/// <exception cref="BluetoothErrorException">Failed to retrieve controllers:.</exception>
public async Task<IEnumerable<string>> ListControllers(CancellationToken cancellationToken = default) // Makes the controller visible to other devices.
{ _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable on", null, cancellationToken).ConfigureAwait(false);
try
{ // Readies the controller for pairing. Remember that you have three minutes after running this command to pair.
var controllers = await ProcessRunner.GetProcessOutputAsync(BcCommand, "list", null, cancellationToken) _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "pairable on", null, cancellationToken).ConfigureAwait(false);
.ConfigureAwait(false);
return controllers.Trim().Split('\n').Select(x => x.Trim()); // Pairs the device with the controller.
} String result = await ProcessRunner.GetProcessOutputAsync(BcCommand, $"pair {deviceAddress}", null, cancellationToken).ConfigureAwait(false);
catch (Exception ex)
{ // Hides the controller from other Bluetooth devices. Otherwise, any device that can detect it has access to it, leaving a major security hole.
throw new BluetoothErrorException($"Failed to retrieve controllers: {ex.Message}"); _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable off", null, cancellationToken).ConfigureAwait(false);
}
} return result.Contains("Paired: yes");
} catch(Exception ex) {
/// <summary> throw new BluetoothErrorException($"Failed to Pair: {ex.Message}");
/// Pairs a specific device with a specific controller. }
/// </summary> }
/// <param name="controllerAddress">The mac address of the controller that will be used to pair.</param>
/// <param name="deviceAddress">The mac address of the device that will be paired.</param> /// <summary>
/// <param name="cancellationToken">The cancellation token.</param> /// Performs a connection of a given controller with a given device.
/// <returns> /// </summary>
/// Returns true or false if the pair was successfully. /// <param name="controllerAddress">The mac address of the controller that will be used to make the connection.</param>
/// </returns> /// <param name="deviceAddress">The mac address of the device that will be connected.</param>
/// <exception cref="BluetoothErrorException">Failed to Pair:.</exception> /// <param name="cancellationToken">The cancellation token.</param>
public async Task<bool> Pair( /// <returns>
string controllerAddress, /// Returns true or false if the connection was successfully.
string deviceAddress, /// </returns>
CancellationToken cancellationToken = default) /// <exception cref="BluetoothErrorException">Failed to connect:.</exception>
{ public async Task<Boolean> Connect(String controllerAddress, String deviceAddress, CancellationToken cancellationToken = default) {
try try {
{ // Selects the controller to pair. Once you select the controller, all controller-related commands will apply to it for three minutes.
// Selects the controller to pair. Once you select the controller, all controller-related commands will apply to it for three minutes. _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, $"select {controllerAddress}", null, cancellationToken).ConfigureAwait(false);
await ProcessRunner
.GetProcessOutputAsync(BcCommand, $"select {controllerAddress}", null, cancellationToken) // Makes the controller visible to other devices.
.ConfigureAwait(false); _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable on", null, cancellationToken).ConfigureAwait(false);
// Makes the controller visible to other devices. // Readies the controller for pairing. Remember that you have three minutes after running this command to pair.
await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable on", null, cancellationToken) _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "pairable on", null, cancellationToken).ConfigureAwait(false);
.ConfigureAwait(false);
// Readies the device for pairing.
// Readies the controller for pairing. Remember that you have three minutes after running this command to pair. String result = await ProcessRunner.GetProcessOutputAsync(BcCommand, $"connect {deviceAddress}", null, cancellationToken).ConfigureAwait(false);
await ProcessRunner.GetProcessOutputAsync(BcCommand, "pairable on", null, cancellationToken)
.ConfigureAwait(false); // Hides the controller from other Bluetooth devices. Otherwise, any device that can detect it has access to it, leaving a major security hole.
_ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable off", null, cancellationToken).ConfigureAwait(false);
// Pairs the device with the controller.
var result = await ProcessRunner return result.Contains("Connected: yes");
.GetProcessOutputAsync(BcCommand, $"pair {deviceAddress}", null, cancellationToken) } catch(Exception ex) {
.ConfigureAwait(false); throw new BluetoothErrorException($"Failed to connect: {ex.Message}");
}
// Hides the controller from other Bluetooth devices. Otherwise, any device that can detect it has access to it, leaving a major security hole. }
await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable off", null, cancellationToken)
.ConfigureAwait(false); /// <summary>
/// Sets the device to re-pair automatically when it is turned on, which eliminates the need to pair all over again.
return result.Contains("Paired: yes"); /// </summary>
} /// <param name="controllerAddress">The mac address of the controller will be used.</param>
catch (Exception ex) /// <param name="deviceAddress">The mac address of the device will be added to the trust list devices.</param>
{ /// <param name="cancellationToken">The cancellation token.</param>
throw new BluetoothErrorException($"Failed to Pair: {ex.Message}"); /// <returns>
} /// Returns true or false if the operation was successful.
} /// </returns>
/// <exception cref="BluetoothErrorException">Failed to add to trust devices list:.</exception>
/// <summary> public async Task<Boolean> Trust(String controllerAddress, String deviceAddress, CancellationToken cancellationToken = default) {
/// Performs a connection of a given controller with a given device. try {
/// </summary> // Selects the controller to pair. Once you select the controller, all controller-related commands will apply to it for three minutes.
/// <param name="controllerAddress">The mac address of the controller that will be used to make the connection.</param> _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, $"select {controllerAddress}", null, cancellationToken).ConfigureAwait(false);
/// <param name="deviceAddress">The mac address of the device that will be connected.</param>
/// <param name="cancellationToken">The cancellation token.</param> // Makes the controller visible to other devices.
/// <returns> _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable on", null, cancellationToken).ConfigureAwait(false);
/// Returns true or false if the connection was successfully.
/// </returns> // Readies the controller for pairing. Remember that you have three minutes after running this command to pair.
/// <exception cref="BluetoothErrorException">Failed to connect:.</exception> _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "pairable on", null, cancellationToken).ConfigureAwait(false);
public async Task<bool> Connect(
string controllerAddress, // Sets the device to re-pair automatically when it is turned on, which eliminates the need to pair all over again.
string deviceAddress, String result = await ProcessRunner.GetProcessOutputAsync(BcCommand, $"trust {deviceAddress}", null, cancellationToken).ConfigureAwait(false);
CancellationToken cancellationToken = default)
{ // Hides the controller from other Bluetooth devices. Otherwise, any device that can detect it has access to it, leaving a major security hole.
try _ = await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable off", null, cancellationToken).ConfigureAwait(false);
{
// Selects the controller to pair. Once you select the controller, all controller-related commands will apply to it for three minutes. return result.Contains("Trusted: yes");
await ProcessRunner } catch(Exception ex) {
.GetProcessOutputAsync(BcCommand, $"select {controllerAddress}", null, cancellationToken) throw new BluetoothErrorException($"Failed to add to trust devices list: {ex.Message}");
.ConfigureAwait(false); }
}
// Makes the controller visible to other devices.
await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable on", null, cancellationToken) /// <summary>
.ConfigureAwait(false); /// Displays information about a particular device.
/// </summary>
// Readies the controller for pairing. Remember that you have three minutes after running this command to pair. /// <param name="deviceAddress">The mac address of the device which info will be retrieved.</param>
await ProcessRunner.GetProcessOutputAsync(BcCommand, "pairable on", null, cancellationToken) /// <param name="cancellationToken">The cancellation token.</param>
.ConfigureAwait(false); /// <returns>
/// Returns the device info.
// Readies the device for pairing. /// </returns>
var result = await ProcessRunner /// <exception cref="BluetoothErrorException">Failed to retrieve info for {deviceAddress}.</exception>
.GetProcessOutputAsync(BcCommand, $"connect {deviceAddress}", null, cancellationToken) public async Task<String> DeviceInfo(String deviceAddress, CancellationToken cancellationToken = default) {
.ConfigureAwait(false); String info = await ProcessRunner.GetProcessOutputAsync(BcCommand, $"info {deviceAddress}", null, cancellationToken).ConfigureAwait(false);
// Hides the controller from other Bluetooth devices. Otherwise, any device that can detect it has access to it, leaving a major security hole. return !String.IsNullOrEmpty(info) ? info : throw new BluetoothErrorException($"Failed to retrieve info for {deviceAddress}");
await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable off", null, cancellationToken) }
.ConfigureAwait(false); }
return result.Contains("Connected: yes");
}
catch (Exception ex)
{
throw new BluetoothErrorException($"Failed to connect: {ex.Message}");
}
}
/// <summary>
/// Sets the device to re-pair automatically when it is turned on, which eliminates the need to pair all over again.
/// </summary>
/// <param name="controllerAddress">The mac address of the controller will be used.</param>
/// <param name="deviceAddress">The mac address of the device will be added to the trust list devices.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// Returns true or false if the operation was successful.
/// </returns>
/// <exception cref="BluetoothErrorException">Failed to add to trust devices list:.</exception>
public async Task<bool> Trust(
string controllerAddress,
string deviceAddress,
CancellationToken cancellationToken = default)
{
try
{
// Selects the controller to pair. Once you select the controller, all controller-related commands will apply to it for three minutes.
await ProcessRunner
.GetProcessOutputAsync(BcCommand, $"select {controllerAddress}", null, cancellationToken)
.ConfigureAwait(false);
// Makes the controller visible to other devices.
await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable on", null, cancellationToken)
.ConfigureAwait(false);
// Readies the controller for pairing. Remember that you have three minutes after running this command to pair.
await ProcessRunner.GetProcessOutputAsync(BcCommand, "pairable on", null, cancellationToken)
.ConfigureAwait(false);
// Sets the device to re-pair automatically when it is turned on, which eliminates the need to pair all over again.
var result = await ProcessRunner
.GetProcessOutputAsync(BcCommand, $"trust {deviceAddress}", null, cancellationToken)
.ConfigureAwait(false);
// Hides the controller from other Bluetooth devices. Otherwise, any device that can detect it has access to it, leaving a major security hole.
await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable off", null, cancellationToken)
.ConfigureAwait(false);
return result.Contains("Trusted: yes");
}
catch (Exception ex)
{
throw new BluetoothErrorException($"Failed to add to trust devices list: {ex.Message}");
}
}
/// <summary>
/// Displays information about a particular device.
/// </summary>
/// <param name="deviceAddress">The mac address of the device which info will be retrieved.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// Returns the device info.
/// </returns>
/// <exception cref="BluetoothErrorException">Failed to retrieve info for {deviceAddress}.</exception>
public async Task<string> DeviceInfo(string deviceAddress, CancellationToken cancellationToken = default)
{
var info = await ProcessRunner
.GetProcessOutputAsync(BcCommand, $"info {deviceAddress}", null, cancellationToken)
.ConfigureAwait(false);
return !string.IsNullOrEmpty(info)
? info
: throw new BluetoothErrorException($"Failed to retrieve info for {deviceAddress}");
}
}
} }

View File

@ -1,71 +1,63 @@
namespace Unosquare.RaspberryIO.Computer using System;
{ using System.Globalization;
using System.Globalization; using System.IO;
using System.IO;
using Swan; using Swan;
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// The Official Raspberry Pi 7-inch touch display from the foundation
/// Some docs available here:
/// http://forums.pimoroni.com/t/official-7-raspberry-pi-touch-screen-faq/959.
/// </summary>
public class DsiDisplay : SingletonBase<DsiDisplay> {
private const String BacklightFilename = "/sys/class/backlight/rpi_backlight/bl_power";
private const String BrightnessFilename = "/sys/class/backlight/rpi_backlight/brightness";
/// <summary> /// <summary>
/// The Official Raspberry Pi 7-inch touch display from the foundation /// Prevents a default instance of the <see cref="DsiDisplay"/> class from being created.
/// Some docs available here:
/// http://forums.pimoroni.com/t/official-7-raspberry-pi-touch-screen-faq/959.
/// </summary> /// </summary>
public class DsiDisplay : SingletonBase<DsiDisplay> private DsiDisplay() {
{ // placeholder
private const string BacklightFilename = "/sys/class/backlight/rpi_backlight/bl_power"; }
private const string BrightnessFilename = "/sys/class/backlight/rpi_backlight/brightness";
/// <summary>
/// <summary> /// Gets a value indicating whether the Pi Foundation Display files are present.
/// Prevents a default instance of the <see cref="DsiDisplay"/> class from being created. /// </summary>
/// </summary> /// <value>
private DsiDisplay() /// <c>true</c> if this instance is present; otherwise, <c>false</c>.
{ /// </value>
// placeholder public Boolean IsPresent => File.Exists(BrightnessFilename);
}
/// <summary>
/// <summary> /// Gets or sets the brightness of the DSI display via filesystem.
/// Gets a value indicating whether the Pi Foundation Display files are present. /// </summary>
/// </summary> /// <value>
/// <value> /// The brightness.
/// <c>true</c> if this instance is present; otherwise, <c>false</c>. /// </value>
/// </value> public Byte Brightness {
public bool IsPresent => File.Exists(BrightnessFilename); get => this.IsPresent ? System.Byte.TryParse(File.ReadAllText(BrightnessFilename).Trim(), out Byte brightness) ? brightness : (Byte)0 : (Byte)0;
set {
/// <summary> if(this.IsPresent) {
/// Gets or sets the brightness of the DSI display via filesystem. File.WriteAllText(BrightnessFilename, value.ToString(CultureInfo.InvariantCulture));
/// </summary> }
/// <value> }
/// The brightness. }
/// </value>
public byte Brightness /// <summary>
{ /// Gets or sets a value indicating whether the backlight of the DSI display on.
get => /// This operation is performed via the file system.
IsPresent /// </summary>
? byte.TryParse(File.ReadAllText(BrightnessFilename).Trim(), out var brightness) ? brightness : (byte)0 : /// <value>
(byte)0; /// <c>true</c> if this instance is backlight on; otherwise, <c>false</c>.
set /// </value>
{ public Boolean IsBacklightOn {
if (IsPresent) get => this.IsPresent && Int32.TryParse(File.ReadAllText(BacklightFilename).Trim(), out Int32 value) && value == 0;
File.WriteAllText(BrightnessFilename, value.ToString(CultureInfo.InvariantCulture)); set {
} if(this.IsPresent) {
} File.WriteAllText(BacklightFilename, value ? "0" : "1");
}
/// <summary> }
/// Gets or sets a value indicating whether the backlight of the DSI display on. }
/// This operation is performed via the file system. }
/// </summary>
/// <value>
/// <c>true</c> if this instance is backlight on; otherwise, <c>false</c>.
/// </value>
public bool IsBacklightOn
{
get =>
IsPresent && (int.TryParse(File.ReadAllText(BacklightFilename).Trim(), out var value) &&
value == 0);
set
{
if (IsPresent)
File.WriteAllText(BacklightFilename, value ? "0" : "1");
}
}
}
} }

View File

@ -1,40 +1,51 @@
namespace Unosquare.RaspberryIO.Computer using System;
{ using System.Net;
using System.Net;
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// Represents a Network Adapter.
/// </summary>
public class NetworkAdapterInfo {
/// <summary> /// <summary>
/// Represents a Network Adapter. /// Gets the name.
/// </summary> /// </summary>
public class NetworkAdapterInfo public String? Name {
{ get; internal set;
/// <summary> }
/// Gets the name.
/// </summary> /// <summary>
public string Name { get; internal set; } /// Gets the IP V4 address.
/// </summary>
/// <summary> public IPAddress? IPv4 {
/// Gets the IP V4 address. get; internal set;
/// </summary> }
public IPAddress IPv4 { get; internal set; }
/// <summary>
/// <summary> /// Gets the IP V6 address.
/// Gets the IP V6 address. /// </summary>
/// </summary> public IPAddress? IPv6 {
public IPAddress IPv6 { get; internal set; } get; internal set;
}
/// <summary>
/// Gets the name of the access point. /// <summary>
/// </summary> /// Gets the name of the access point.
public string AccessPointName { get; internal set; } /// </summary>
public String? AccessPointName {
/// <summary> get; internal set;
/// Gets the MAC (Physical) address. }
/// </summary>
public string MacAddress { get; internal set; } /// <summary>
/// Gets the MAC (Physical) address.
/// <summary> /// </summary>
/// Gets a value indicating whether this instance is wireless. public String? MacAddress {
/// </summary> get; internal set;
public bool IsWireless { get; internal set; } }
}
/// <summary>
/// Gets a value indicating whether this instance is wireless.
/// </summary>
public Boolean IsWireless {
get; internal set;
}
}
} }

View File

@ -1,281 +1,271 @@
namespace Unosquare.RaspberryIO.Computer using System;
{ using System.Collections.Generic;
using Swan; using System.IO;
using Swan.Logging; using System.Linq;
using Swan.Net; using System.Net;
using System; using System.Text;
using System.Collections.Generic; using System.Threading.Tasks;
using System.IO;
using System.Linq; using Swan;
using System.Net; using Swan.Logging;
using System.Text; using Swan.Net;
using System.Threading.Tasks;
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// Represents the network information.
/// </summary>
public class NetworkSettings : SingletonBase<NetworkSettings> {
private const String EssidTag = "ESSID:";
/// <summary> /// <summary>
/// Represents the network information. /// Gets the local machine Host Name.
/// </summary> /// </summary>
public class NetworkSettings : SingletonBase<NetworkSettings> public String HostName => Network.HostName;
{
private const string EssidTag = "ESSID:"; /// <summary>
/// Retrieves the wireless networks.
/// <summary> /// </summary>
/// Gets the local machine Host Name. /// <param name="adapter">The adapter.</param>
/// </summary> /// <returns>A list of WiFi networks.</returns>
public string HostName => Network.HostName; public Task<List<WirelessNetworkInfo>> RetrieveWirelessNetworks(String adapter) => this.RetrieveWirelessNetworks(new[] { adapter });
/// <summary> /// <summary>
/// Retrieves the wireless networks. /// Retrieves the wireless networks.
/// </summary> /// </summary>
/// <param name="adapter">The adapter.</param> /// <param name="adapters">The adapters.</param>
/// <returns>A list of WiFi networks.</returns> /// <returns>A list of WiFi networks.</returns>
public Task<List<WirelessNetworkInfo>> RetrieveWirelessNetworks(string adapter) => RetrieveWirelessNetworks(new[] { adapter }); public async Task<List<WirelessNetworkInfo>> RetrieveWirelessNetworks(String[]? adapters = null) {
List<WirelessNetworkInfo> result = new List<WirelessNetworkInfo>();
/// <summary>
/// Retrieves the wireless networks. foreach(String? networkAdapter in adapters ?? (await this.RetrieveAdapters()).Where(x => x.IsWireless).Select(x => x.Name)) {
/// </summary> String wirelessOutput = await ProcessRunner.GetProcessOutputAsync("iwlist", $"{networkAdapter} scanning").ConfigureAwait(false);
/// <param name="adapters">The adapters.</param> String[] outputLines = wirelessOutput.Split('\n').Select(x => x.Trim()).Where(x => String.IsNullOrWhiteSpace(x) == false).ToArray();
/// <returns>A list of WiFi networks.</returns>
public async Task<List<WirelessNetworkInfo>> RetrieveWirelessNetworks(string[] adapters = null) for(Int32 i = 0; i < outputLines.Length; i++) {
{ String line = outputLines[i];
var result = new List<WirelessNetworkInfo>();
if(line.StartsWith(EssidTag) == false) {
foreach (var networkAdapter in adapters ?? (await RetrieveAdapters()).Where(x => x.IsWireless).Select(x => x.Name)) continue;
{ }
var wirelessOutput = await ProcessRunner.GetProcessOutputAsync("iwlist", $"{networkAdapter} scanning").ConfigureAwait(false);
var outputLines = WirelessNetworkInfo network = new WirelessNetworkInfo {
wirelessOutput.Split('\n') Name = line.Replace(EssidTag, String.Empty).Replace("\"", String.Empty)
.Select(x => x.Trim()) };
.Where(x => string.IsNullOrWhiteSpace(x) == false)
.ToArray(); while(true) {
if(i + 1 >= outputLines.Length) {
for (var i = 0; i < outputLines.Length; i++) break;
{ }
var line = outputLines[i];
// should look for two lines before the ESSID acording to the scan
if (line.StartsWith(EssidTag) == false) continue; line = outputLines[i - 2];
var network = new WirelessNetworkInfo if(!line.StartsWith("Quality=")) {
{ continue;
Name = line.Replace(EssidTag, string.Empty).Replace("\"", string.Empty) }
};
network.Quality = line.Replace("Quality=", String.Empty);
while (true) break;
{ }
if (i + 1 >= outputLines.Length) break;
while(true) {
// should look for two lines before the ESSID acording to the scan if(i + 1 >= outputLines.Length) {
line = outputLines[i - 2]; break;
}
if (!line.StartsWith("Quality=")) continue;
network.Quality = line.Replace("Quality=", string.Empty); // should look for a line before the ESSID acording to the scan
break; line = outputLines[i - 1];
}
if(!line.StartsWith("Encryption key:")) {
while (true) continue;
{ }
if (i + 1 >= outputLines.Length) break;
network.IsEncrypted = line.Replace("Encryption key:", String.Empty).Trim() == "on";
// should look for a line before the ESSID acording to the scan break;
line = outputLines[i - 1]; }
if (!line.StartsWith("Encryption key:")) continue; if(result.Any(x => x.Name == network.Name) == false) {
network.IsEncrypted = line.Replace("Encryption key:", string.Empty).Trim() == "on"; result.Add(network);
break; }
} }
}
if (result.Any(x => x.Name == network.Name) == false)
result.Add(network); return result
} .OrderBy(x => x.Name)
} .ToList();
}
return result
.OrderBy(x => x.Name) /// <summary>
.ToList(); /// Setups the wireless network.
} /// </summary>
/// <param name="adapterName">Name of the adapter.</param>
/// <summary> /// <param name="networkSsid">The network ssid.</param>
/// Setups the wireless network. /// <param name="password">The password (8 characters as minimum length).</param>
/// </summary> /// <param name="countryCode">The 2-letter country code in uppercase. Default is US.</param>
/// <param name="adapterName">Name of the adapter.</param> /// <returns>True if successful. Otherwise, false.</returns>
/// <param name="networkSsid">The network ssid.</param> public async Task<Boolean> SetupWirelessNetwork(String adapterName, String networkSsid, String? password = null, String countryCode = "US") {
/// <param name="password">The password (8 characters as minimum length).</param> // TODO: Get the country where the device is located to set 'country' param in payload var
/// <param name="countryCode">The 2-letter country code in uppercase. Default is US.</param> String payload = $"country={countryCode}\nctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\nupdate_config=1\n";
/// <returns>True if successful. Otherwise, false.</returns>
public async Task<bool> SetupWirelessNetwork(string adapterName, string networkSsid, string password = null, string countryCode = "US") if(!String.IsNullOrWhiteSpace(password) && password.Length < 8) {
{ throw new InvalidOperationException("The password must be at least 8 characters length.");
// TODO: Get the country where the device is located to set 'country' param in payload var }
var payload = $"country={countryCode}\nctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\nupdate_config=1\n";
payload += String.IsNullOrEmpty(password)
if (!string.IsNullOrWhiteSpace(password) && password.Length < 8) ? $"network={{\n\tssid=\"{networkSsid}\"\n\tkey_mgmt=NONE\n\t}}\n"
throw new InvalidOperationException("The password must be at least 8 characters length."); : $"network={{\n\tssid=\"{networkSsid}\"\n\tpsk=\"{password}\"\n\t}}\n";
try {
payload += string.IsNullOrEmpty(password) File.WriteAllText("/etc/wpa_supplicant/wpa_supplicant.conf", payload);
? $"network={{\n\tssid=\"{networkSsid}\"\n\tkey_mgmt=NONE\n\t}}\n" _ = await ProcessRunner.GetProcessOutputAsync("pkill", "-f wpa_supplicant");
: $"network={{\n\tssid=\"{networkSsid}\"\n\tpsk=\"{password}\"\n\t}}\n"; _ = await ProcessRunner.GetProcessOutputAsync("ifdown", adapterName);
try _ = await ProcessRunner.GetProcessOutputAsync("ifup", adapterName);
{ } catch(Exception ex) {
File.WriteAllText("/etc/wpa_supplicant/wpa_supplicant.conf", payload); ex.Log(nameof(NetworkSettings));
await ProcessRunner.GetProcessOutputAsync("pkill", "-f wpa_supplicant"); return false;
await ProcessRunner.GetProcessOutputAsync("ifdown", adapterName); }
await ProcessRunner.GetProcessOutputAsync("ifup", adapterName);
} return true;
catch (Exception ex) }
{
ex.Log(nameof(NetworkSettings)); /// <summary>
return false; /// Retrieves the network adapters.
} /// </summary>
/// <returns>A list of network adapters.</returns>
return true; public async Task<List<NetworkAdapterInfo>> RetrieveAdapters() {
} const String hWaddr = "HWaddr ";
const String ether = "ether ";
/// <summary>
/// Retrieves the network adapters. List<NetworkAdapterInfo> result = new List<NetworkAdapterInfo>();
/// </summary> String interfacesOutput = await ProcessRunner.GetProcessOutputAsync("ifconfig");
/// <returns>A list of network adapters.</returns> String[] wlanOutput = (await ProcessRunner.GetProcessOutputAsync("iwconfig")).Split('\n').Where(x => x.Contains("no wireless extensions.") == false).ToArray();
public async Task<List<NetworkAdapterInfo>> RetrieveAdapters()
{ String[] outputLines = interfacesOutput.Split('\n').Where(x => String.IsNullOrWhiteSpace(x) == false).ToArray();
const string hWaddr = "HWaddr ";
const string ether = "ether "; for(Int32 i = 0; i < outputLines.Length; i++) {
// grab the current line
var result = new List<NetworkAdapterInfo>(); String line = outputLines[i];
var interfacesOutput = await ProcessRunner.GetProcessOutputAsync("ifconfig");
var wlanOutput = (await ProcessRunner.GetProcessOutputAsync("iwconfig")) // skip if the line is indented
.Split('\n') if(Char.IsLetterOrDigit(line[0]) == false) {
.Where(x => x.Contains("no wireless extensions.") == false) continue;
.ToArray(); }
var outputLines = interfacesOutput.Split('\n').Where(x => string.IsNullOrWhiteSpace(x) == false).ToArray(); // Read the line as an adapter
NetworkAdapterInfo adapter = new NetworkAdapterInfo {
for (var i = 0; i < outputLines.Length; i++) Name = line.Substring(0, line.IndexOf(' ')).TrimEnd(':')
{ };
// grab the current line
var line = outputLines[i]; // Parse the MAC address in old version of ifconfig; it comes in the first line
if(line.IndexOf(hWaddr, StringComparison.Ordinal) >= 0) {
// skip if the line is indented Int32 startIndexHwd = line.IndexOf(hWaddr, StringComparison.Ordinal) + hWaddr.Length;
if (char.IsLetterOrDigit(line[0]) == false) adapter.MacAddress = line.Substring(startIndexHwd, 17).Trim();
continue; }
// Read the line as an adapter // Parse the info in lines other than the first
var adapter = new NetworkAdapterInfo for(Int32 j = i + 1; j < outputLines.Length; j++) {
{ // Get the contents of the indented line
Name = line.Substring(0, line.IndexOf(' ')).TrimEnd(':') String indentedLine = outputLines[j];
};
// We have hit the next adapter info
// Parse the MAC address in old version of ifconfig; it comes in the first line if(Char.IsLetterOrDigit(indentedLine[0])) {
if (line.IndexOf(hWaddr, StringComparison.Ordinal) >= 0) i = j - 1;
{ break;
var startIndexHwd = line.IndexOf(hWaddr, StringComparison.Ordinal) + hWaddr.Length; }
adapter.MacAddress = line.Substring(startIndexHwd, 17).Trim();
} // Parse the MAC address in new versions of ifconfig; it no longer comes in the first line
if(indentedLine.IndexOf(ether, StringComparison.Ordinal) >= 0 && String.IsNullOrWhiteSpace(adapter.MacAddress)) {
// Parse the info in lines other than the first Int32 startIndexHwd = indentedLine.IndexOf(ether, StringComparison.Ordinal) + ether.Length;
for (var j = i + 1; j < outputLines.Length; j++) adapter.MacAddress = indentedLine.Substring(startIndexHwd, 17).Trim();
{ }
// Get the contents of the indented line
var indentedLine = outputLines[j]; // Parse the IPv4 Address
GetIPv4(indentedLine, adapter);
// We have hit the next adapter info
if (char.IsLetterOrDigit(indentedLine[0])) // Parse the IPv6 Address
{ GetIPv6(indentedLine, adapter);
i = j - 1;
break; // we have hit the end of the output in an indented line
} if(j >= outputLines.Length - 1) {
i = outputLines.Length;
// Parse the MAC address in new versions of ifconfig; it no longer comes in the first line }
if (indentedLine.IndexOf(ether, StringComparison.Ordinal) >= 0 && string.IsNullOrWhiteSpace(adapter.MacAddress)) }
{
var startIndexHwd = indentedLine.IndexOf(ether, StringComparison.Ordinal) + ether.Length; // Retrieve the wireless LAN info
adapter.MacAddress = indentedLine.Substring(startIndexHwd, 17).Trim(); String wlanInfo = wlanOutput.FirstOrDefault(x => x.StartsWith(adapter.Name));
}
if(wlanInfo != null) {
// Parse the IPv4 Address adapter.IsWireless = true;
GetIPv4(indentedLine, adapter); String[] essidParts = wlanInfo.Split(new[] { EssidTag }, StringSplitOptions.RemoveEmptyEntries);
if(essidParts.Length >= 2) {
// Parse the IPv6 Address adapter.AccessPointName = essidParts[1].Replace("\"", String.Empty).Trim();
GetIPv6(indentedLine, adapter); }
}
// we have hit the end of the output in an indented line
if (j >= outputLines.Length - 1) // Add the current adapter to the result
i = outputLines.Length; result.Add(adapter);
} }
// Retrieve the wireless LAN info return result.OrderBy(x => x.Name).ToList();
var wlanInfo = wlanOutput.FirstOrDefault(x => x.StartsWith(adapter.Name)); }
if (wlanInfo != null) /// <summary>
{ /// Retrieves the current network adapter.
adapter.IsWireless = true; /// </summary>
var essidParts = wlanInfo.Split(new[] { EssidTag }, StringSplitOptions.RemoveEmptyEntries); /// <returns>The name of the current network adapter.</returns>
if (essidParts.Length >= 2) public static async Task<String?> GetCurrentAdapterName() {
{ String result = await ProcessRunner.GetProcessOutputAsync("route").ConfigureAwait(false);
adapter.AccessPointName = essidParts[1].Replace("\"", string.Empty).Trim(); String defaultLine = result.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(l => l.StartsWith("default", StringComparison.OrdinalIgnoreCase));
}
} return defaultLine?.Trim().Substring(defaultLine.LastIndexOf(" ", StringComparison.OrdinalIgnoreCase) + 1);
}
// Add the current adapter to the result
result.Add(adapter); /// <summary>
} /// Retrieves current wireless connected network name.
/// </summary>
return result.OrderBy(x => x.Name).ToList(); /// <returns>The connected network name.</returns>
} public Task<String> GetWirelessNetworkName() => ProcessRunner.GetProcessOutputAsync("iwgetid", "-r");
/// <summary> private static void GetIPv4(String indentedLine, NetworkAdapterInfo adapter) {
/// Retrieves the current network adapter. String? addressText = ParseOutputTagFromLine(indentedLine, "inet addr:") ?? ParseOutputTagFromLine(indentedLine, "inet ");
/// </summary>
/// <returns>The name of the current network adapter.</returns> if(addressText == null) {
public static async Task<string> GetCurrentAdapterName() return;
{ }
var result = await ProcessRunner.GetProcessOutputAsync("route").ConfigureAwait(false);
var defaultLine = result.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries) if(IPAddress.TryParse(addressText, out IPAddress outValue)) {
.FirstOrDefault(l => l.StartsWith("default", StringComparison.OrdinalIgnoreCase)); adapter.IPv4 = outValue;
}
return defaultLine?.Trim().Substring(defaultLine.LastIndexOf(" ", StringComparison.OrdinalIgnoreCase) + 1); }
}
private static void GetIPv6(String indentedLine, NetworkAdapterInfo adapter) {
/// <summary> String? addressText = ParseOutputTagFromLine(indentedLine, "inet6 addr:") ?? ParseOutputTagFromLine(indentedLine, "inet6 ");
/// Retrieves current wireless connected network name.
/// </summary> if(addressText == null) {
/// <returns>The connected network name.</returns> return;
public Task<string> GetWirelessNetworkName() => ProcessRunner.GetProcessOutputAsync("iwgetid", "-r"); }
private static void GetIPv4(string indentedLine, NetworkAdapterInfo adapter) if(IPAddress.TryParse(addressText, out IPAddress outValue)) {
{ adapter.IPv6 = outValue;
var addressText = ParseOutputTagFromLine(indentedLine, "inet addr:") ?? }
ParseOutputTagFromLine(indentedLine, "inet "); }
if (addressText == null) return; private static String? ParseOutputTagFromLine(String indentedLine, String tagName) {
if (IPAddress.TryParse(addressText, out var outValue)) if(indentedLine.IndexOf(tagName, StringComparison.Ordinal) < 0) {
adapter.IPv4 = outValue; return null;
} }
private static void GetIPv6(string indentedLine, NetworkAdapterInfo adapter) Int32 startIndex = indentedLine.IndexOf(tagName, StringComparison.Ordinal) + tagName.Length;
{ StringBuilder builder = new StringBuilder(1024);
var addressText = ParseOutputTagFromLine(indentedLine, "inet6 addr:") ?? for(Int32 c = startIndex; c < indentedLine.Length; c++) {
ParseOutputTagFromLine(indentedLine, "inet6 "); Char currentChar = indentedLine[c];
if(!Char.IsPunctuation(currentChar) && !Char.IsLetterOrDigit(currentChar)) {
if (addressText == null) return; break;
}
if (IPAddress.TryParse(addressText, out var outValue))
adapter.IPv6 = outValue; _ = builder.Append(currentChar);
} }
private static string ParseOutputTagFromLine(string indentedLine, string tagName) return builder.ToString();
{ }
if (indentedLine.IndexOf(tagName, StringComparison.Ordinal) < 0) }
return null;
var startIndex = indentedLine.IndexOf(tagName, StringComparison.Ordinal) + tagName.Length;
var builder = new StringBuilder(1024);
for (var c = startIndex; c < indentedLine.Length; c++)
{
var currentChar = indentedLine[c];
if (!char.IsPunctuation(currentChar) && !char.IsLetterOrDigit(currentChar))
break;
builder.Append(currentChar);
}
return builder.ToString();
}
}
} }

View File

@ -1,46 +1,58 @@
namespace Unosquare.RaspberryIO.Computer using System;
{
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// Represents the OS Information.
/// </summary>
public class OsInfo {
/// <summary> /// <summary>
/// Represents the OS Information. /// System name.
/// </summary> /// </summary>
public class OsInfo public String? SysName {
{ get; set;
/// <summary> }
/// System name.
/// </summary> /// <summary>
public string SysName { get; set; } /// Node name.
/// </summary>
/// <summary> public String? NodeName {
/// Node name. get; set;
/// </summary> }
public string NodeName { get; set; }
/// <summary>
/// <summary> /// Release level.
/// Release level. /// </summary>
/// </summary> public String? Release {
public string Release { get; set; } get; set;
}
/// <summary>
/// Version level. /// <summary>
/// </summary> /// Version level.
public string Version { get; set; } /// </summary>
public String? Version {
/// <summary> get; set;
/// Hardware level. }
/// </summary>
public string Machine { get; set; } /// <summary>
/// Hardware level.
/// <summary> /// </summary>
/// Domain name. public String? Machine {
/// </summary> get; set;
public string DomainName { get; set; } }
/// <summary> /// <summary>
/// Returns a <see cref="string" /> that represents this instance. /// Domain name.
/// </summary> /// </summary>
/// <returns> public String? DomainName {
/// A <see cref="string" /> that represents this instance. get; set;
/// </returns> }
public override string ToString() => $"{SysName} {Release} {Version}";
} /// <summary>
/// Returns a <see cref="String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="String" /> that represents this instance.
/// </returns>
public override String ToString() => $"{this.SysName} {this.Release} {this.Version}";
}
} }

View File

@ -1,394 +1,388 @@
namespace Unosquare.RaspberryIO.Computer namespace Unosquare.RaspberryIO.Computer {
{ /// <summary>
/// Defines the board revision codes of the different versions of the Raspberry Pi
/// http://www.raspberrypi-spy.co.uk/2012/09/checking-your-raspberry-pi-board-version/.
/// https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md.
/// </summary>
public enum PiVersion {
/// <summary> /// <summary>
/// Defines the board revision codes of the different versions of the Raspberry Pi /// The unknown version
/// http://www.raspberrypi-spy.co.uk/2012/09/checking-your-raspberry-pi-board-version/.
/// https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md.
/// </summary> /// </summary>
public enum PiVersion Unknown = 0,
{
/// <summary>
/// The unknown version
/// </summary>
Unknown = 0,
/// <summary>
/// The model B Rev1
/// </summary>
ModelBRev1 = 0x0002,
/// <summary>
/// The model B Rev1 ECN0001
/// </summary>
ModelBRev1ECN0001 = 0x0003,
/// <summary>
/// The model B Rev2 Sony
/// </summary>
ModelBRev2x04 = 0x0004,
/// <summary>
/// The model B Rev2 Qisda
/// </summary>
ModelBRev2x05 = 0x0005,
/// <summary>
/// The model B Rev2 Egoman
/// </summary>
ModelBRev2x06 = 0x0006,
/// <summary>
/// The model A Rev2 Egoman
/// </summary>
ModelAx07 = 0x0007,
/// <summary>
/// The model A Rev2 Sony
/// </summary>
ModelAx08 = 0x0008,
/// <summary>
/// The model A Rev2 Qisda
/// </summary>
ModelAx09 = 0x0009,
/// <summary>
/// The model B Rev2 (512MB) Egoman
/// </summary>
ModelBRev2x0d = 0x000d,
/// <summary>
/// The model B Rev2 (512MB) Sony
/// </summary>
ModelBRev2x0e = 0x000e,
/// <summary>
/// The model B Rev2 (512MB) Egoman
/// </summary>
ModelBRev2x0f = 0x000f,
/// <summary>
/// The model B+ Rev1 Sony
/// </summary>
ModelBPlus0x10 = 0x0010,
/// <summary>
/// The compute module 1 Sony
/// </summary>
ComputeModule0x11 = 0x0011,
/// <summary>
/// The model A+ Rev1.1 Sony
/// </summary>
ModelAPlus0x12 = 0x0012,
/// <summary>
/// The model B+ Rev1.2 Embest
/// </summary>
ModelBPlus0x13 = 0x0013,
/// <summary>
/// The compute module 1 Embest
/// </summary>
ComputeModule0x14 = 0x0014,
/// <summary>
/// The model A+ Rev1.1 Embest
/// </summary>
ModelAPlus0x15 = 0x0015,
/// <summary>
/// The model A+ Rev1.1 (512MB) Sony
/// </summary>
ModelAPlus1v1Sony = 900021,
/// <summary>
/// The model B+ Rev1.2 sony
/// </summary>
ModelBPlus1v2Sony = 900032,
/// <summary>
/// The Pi Zero Rev1.2 Sony
/// </summary>
PiZero1v2 = 0x900092,
/// <summary>
/// The Pi Zero Rev1.3 SOny
/// </summary>
PiZero1v3 = 0x900093,
/// <summary>
/// The Pi Zero W Rev1.1
/// </summary>
PiZeroW = 0x9000c1,
/// <summary>
/// The Pi 3 model A+ Sony
/// </summary>
Pi3ModelAPlus = 0x9020e0,
/// <summary>
/// The Pi Zero Rev1.2 Embest
/// </summary>
PiZero1v2Embest = 0x920092,
/// <summary>
/// The Pi Zero Rev1.3 Embest
/// </summary>
PiZero1v3Embest = 0x920093,
/// <summary>
/// The Pi 2 model B Rev1.0 Sony
/// </summary>
Pi2ModelB1v0Sony = 0xa01040,
/// <summary>
/// The Pi 2 model B Rev1.1 Sony
/// </summary>
Pi2ModelB1v1Sony = 0xa01041,
/// <summary>
/// The Pi 3 model B Rev1.2 Sony
/// </summary>
Pi3ModelBSony = 0xa02082,
/// <summary>
/// The compute module 3 Rev1.0 Sony
/// </summary>
ComputeModule3Sony = 0xa020a0,
/// <summary>
/// The Pi 3 model B+ Rev1.3 Sony
/// </summary>
Pi3ModelBPlusSony = 0xa020d3,
/// <summary>
/// The Pi 2 model B Rev1.1 Embest
/// </summary>
Pi2ModelB1v1Embest = 0xa21041,
/// <summary>
/// The Pi 2 model B Rev1.2 Embest
/// </summary>
Pi2ModelB1v2 = 0xa22042,
/// <summary>
/// The Pi 3 model B Rev1.2 Embest
/// </summary>
Pi3ModelBEmbest = 0xa22082,
/// <summary>
/// The compute module 3 Rev1.0 Embest
/// </summary>
ComputeModule3Embest = 0xa220a0,
/// <summary>
/// The Pi 3 model B Rev1.2 Sony Japan
/// </summary>
Pi3ModelBSonyJapan = 0xa32082,
/// <summary>
/// The Pi 3 model B Rev1.2 Stadium
/// </summary>
Pi3ModelBStadium = 0xa52082,
/// <summary>
/// The compute module 3+ Rev 1.0 Sony
/// </summary>
ComputeModule3PlusSony = 0xa02100,
/// <summary>
/// The Pi 4 model B 1GB, Sony
/// </summary>
Pi4ModelB1Gb = 0xa03111,
/// <summary>
/// The Pi 4 model B 2GB, Sony
/// </summary>
Pi4ModelB2Gb = 0xb03111,
/// <summary>
/// The Pi 4 model B 4GB, Sony
/// </summary>
Pi4ModelB4Gb = 0xc03111,
}
/// <summary> /// <summary>
/// Defines the board model accordingly to new-style revision codes. /// The model B Rev1
/// </summary> /// </summary>
public enum BoardModel ModelBRev1 = 0x0002,
{
/// <summary>
/// Model A
/// </summary>
ModelA = 0,
/// <summary>
/// Model B
/// </summary>
ModelB = 1,
/// <summary>
/// Model A+
/// </summary>
ModelAPlus = 2,
/// <summary>
/// Model B+
/// </summary>
ModelBPlus = 3,
/// <summary>
/// Model 2B
/// </summary>
Model2B = 4,
/// <summary>
/// Alpha (early prototype)
/// </summary>
Alpha = 5,
/// <summary>
/// Compute Module 1
/// </summary>
CM1 = 6,
/// <summary>
/// Model 3B
/// </summary>
Model3B = 8,
/// <summary>
/// Model Zero
/// </summary>
Zero = 9,
/// <summary>
/// Compute Module 3
/// </summary>
CM3 = 0xa,
/// <summary>
/// Model Zero W
/// </summary>
ZeroW = 0xc,
/// <summary>
/// Model 3B+
/// </summary>
Model3BPlus = 0xd,
/// <summary>
/// Model 3A+
/// </summary>
Model3APlus = 0xe,
/// <summary>
/// Reserved (Internal use only)
/// </summary>
InternalUse = 0xf,
/// <summary>
/// Compute Module 3+
/// </summary>
CM3Plus = 0x10,
/// <summary>
/// Model 4B
/// </summary>
Model4B = 0x11,
}
/// <summary> /// <summary>
/// Defines the processor model accordingly to new-style revision codes. /// The model B Rev1 ECN0001
/// </summary> /// </summary>
public enum ProcessorModel ModelBRev1ECN0001 = 0x0003,
{
/// <summary>
/// The BCMM2835 processor.
/// </summary>
BCM2835,
/// <summary>
/// The BCMM2836 processor.
/// </summary>
BCM2836,
/// <summary>
/// The BCMM2837 processor.
/// </summary>
BCM2837,
/// <summary>
/// The BCM2711 processor.
/// </summary>
BCM2711,
}
/// <summary> /// <summary>
/// Defines the manufacturer accordingly to new-style revision codes. /// The model B Rev2 Sony
/// </summary> /// </summary>
public enum Manufacturer ModelBRev2x04 = 0x0004,
{
/// <summary>
/// Sony UK
/// </summary>
SonyUK,
/// <summary>
/// Egoman
/// </summary>
Egoman,
/// <summary>
/// Embest
/// </summary>
Embest,
/// <summary>
/// Sony Japan
/// </summary>
SonyJapan,
/// <summary>
/// Embest
/// </summary>
Embest2,
/// <summary>
/// Stadium
/// </summary>
Stadium,
}
/// <summary> /// <summary>
/// Defines the memory size accordingly to new-style revision codes. /// The model B Rev2 Qisda
/// </summary> /// </summary>
public enum MemorySize ModelBRev2x05 = 0x0005,
{
/// <summary> /// <summary>
/// 256 MB /// The model B Rev2 Egoman
/// </summary> /// </summary>
Memory256, ModelBRev2x06 = 0x0006,
/// <summary> /// <summary>
/// 512 MB /// The model A Rev2 Egoman
/// </summary> /// </summary>
Memory512, ModelAx07 = 0x0007,
/// <summary> /// <summary>
/// 1 GB /// The model A Rev2 Sony
/// </summary> /// </summary>
Memory1024, ModelAx08 = 0x0008,
/// <summary> /// <summary>
/// 2 GB /// The model A Rev2 Qisda
/// </summary> /// </summary>
Memory2048, ModelAx09 = 0x0009,
/// <summary> /// <summary>
/// 4 GB /// The model B Rev2 (512MB) Egoman
/// </summary> /// </summary>
Memory4096, ModelBRev2x0d = 0x000d,
}
/// <summary>
/// The model B Rev2 (512MB) Sony
/// </summary>
ModelBRev2x0e = 0x000e,
/// <summary>
/// The model B Rev2 (512MB) Egoman
/// </summary>
ModelBRev2x0f = 0x000f,
/// <summary>
/// The model B+ Rev1 Sony
/// </summary>
ModelBPlus0x10 = 0x0010,
/// <summary>
/// The compute module 1 Sony
/// </summary>
ComputeModule0x11 = 0x0011,
/// <summary>
/// The model A+ Rev1.1 Sony
/// </summary>
ModelAPlus0x12 = 0x0012,
/// <summary>
/// The model B+ Rev1.2 Embest
/// </summary>
ModelBPlus0x13 = 0x0013,
/// <summary>
/// The compute module 1 Embest
/// </summary>
ComputeModule0x14 = 0x0014,
/// <summary>
/// The model A+ Rev1.1 Embest
/// </summary>
ModelAPlus0x15 = 0x0015,
/// <summary>
/// The model A+ Rev1.1 (512MB) Sony
/// </summary>
ModelAPlus1v1Sony = 900021,
/// <summary>
/// The model B+ Rev1.2 sony
/// </summary>
ModelBPlus1v2Sony = 900032,
/// <summary>
/// The Pi Zero Rev1.2 Sony
/// </summary>
PiZero1v2 = 0x900092,
/// <summary>
/// The Pi Zero Rev1.3 SOny
/// </summary>
PiZero1v3 = 0x900093,
/// <summary>
/// The Pi Zero W Rev1.1
/// </summary>
PiZeroW = 0x9000c1,
/// <summary>
/// The Pi 3 model A+ Sony
/// </summary>
Pi3ModelAPlus = 0x9020e0,
/// <summary>
/// The Pi Zero Rev1.2 Embest
/// </summary>
PiZero1v2Embest = 0x920092,
/// <summary>
/// The Pi Zero Rev1.3 Embest
/// </summary>
PiZero1v3Embest = 0x920093,
/// <summary>
/// The Pi 2 model B Rev1.0 Sony
/// </summary>
Pi2ModelB1v0Sony = 0xa01040,
/// <summary>
/// The Pi 2 model B Rev1.1 Sony
/// </summary>
Pi2ModelB1v1Sony = 0xa01041,
/// <summary>
/// The Pi 3 model B Rev1.2 Sony
/// </summary>
Pi3ModelBSony = 0xa02082,
/// <summary>
/// The compute module 3 Rev1.0 Sony
/// </summary>
ComputeModule3Sony = 0xa020a0,
/// <summary>
/// The Pi 3 model B+ Rev1.3 Sony
/// </summary>
Pi3ModelBPlusSony = 0xa020d3,
/// <summary>
/// The Pi 2 model B Rev1.1 Embest
/// </summary>
Pi2ModelB1v1Embest = 0xa21041,
/// <summary>
/// The Pi 2 model B Rev1.2 Embest
/// </summary>
Pi2ModelB1v2 = 0xa22042,
/// <summary>
/// The Pi 3 model B Rev1.2 Embest
/// </summary>
Pi3ModelBEmbest = 0xa22082,
/// <summary>
/// The compute module 3 Rev1.0 Embest
/// </summary>
ComputeModule3Embest = 0xa220a0,
/// <summary>
/// The Pi 3 model B Rev1.2 Sony Japan
/// </summary>
Pi3ModelBSonyJapan = 0xa32082,
/// <summary>
/// The Pi 3 model B Rev1.2 Stadium
/// </summary>
Pi3ModelBStadium = 0xa52082,
/// <summary>
/// The compute module 3+ Rev 1.0 Sony
/// </summary>
ComputeModule3PlusSony = 0xa02100,
/// <summary>
/// The Pi 4 model B 1GB, Sony
/// </summary>
Pi4ModelB1Gb = 0xa03111,
/// <summary>
/// The Pi 4 model B 2GB, Sony
/// </summary>
Pi4ModelB2Gb = 0xb03111,
/// <summary>
/// The Pi 4 model B 4GB, Sony
/// </summary>
Pi4ModelB4Gb = 0xc03111,
}
/// <summary>
/// Defines the board model accordingly to new-style revision codes.
/// </summary>
public enum BoardModel {
/// <summary>
/// Model A
/// </summary>
ModelA = 0,
/// <summary>
/// Model B
/// </summary>
ModelB = 1,
/// <summary>
/// Model A+
/// </summary>
ModelAPlus = 2,
/// <summary>
/// Model B+
/// </summary>
ModelBPlus = 3,
/// <summary>
/// Model 2B
/// </summary>
Model2B = 4,
/// <summary>
/// Alpha (early prototype)
/// </summary>
Alpha = 5,
/// <summary>
/// Compute Module 1
/// </summary>
CM1 = 6,
/// <summary>
/// Model 3B
/// </summary>
Model3B = 8,
/// <summary>
/// Model Zero
/// </summary>
Zero = 9,
/// <summary>
/// Compute Module 3
/// </summary>
CM3 = 0xa,
/// <summary>
/// Model Zero W
/// </summary>
ZeroW = 0xc,
/// <summary>
/// Model 3B+
/// </summary>
Model3BPlus = 0xd,
/// <summary>
/// Model 3A+
/// </summary>
Model3APlus = 0xe,
/// <summary>
/// Reserved (Internal use only)
/// </summary>
InternalUse = 0xf,
/// <summary>
/// Compute Module 3+
/// </summary>
CM3Plus = 0x10,
/// <summary>
/// Model 4B
/// </summary>
Model4B = 0x11,
}
/// <summary>
/// Defines the processor model accordingly to new-style revision codes.
/// </summary>
public enum ProcessorModel {
/// <summary>
/// The BCMM2835 processor.
/// </summary>
BCM2835,
/// <summary>
/// The BCMM2836 processor.
/// </summary>
BCM2836,
/// <summary>
/// The BCMM2837 processor.
/// </summary>
BCM2837,
/// <summary>
/// The BCM2711 processor.
/// </summary>
BCM2711,
}
/// <summary>
/// Defines the manufacturer accordingly to new-style revision codes.
/// </summary>
public enum Manufacturer {
/// <summary>
/// Sony UK
/// </summary>
SonyUK,
/// <summary>
/// Egoman
/// </summary>
Egoman,
/// <summary>
/// Embest
/// </summary>
Embest,
/// <summary>
/// Sony Japan
/// </summary>
SonyJapan,
/// <summary>
/// Embest
/// </summary>
Embest2,
/// <summary>
/// Stadium
/// </summary>
Stadium,
}
/// <summary>
/// Defines the memory size accordingly to new-style revision codes.
/// </summary>
public enum MemorySize {
/// <summary>
/// 256 MB
/// </summary>
Memory256,
/// <summary>
/// 512 MB
/// </summary>
Memory512,
/// <summary>
/// 1 GB
/// </summary>
Memory1024,
/// <summary>
/// 2 GB
/// </summary>
Memory2048,
/// <summary>
/// 4 GB
/// </summary>
Memory4096,
}
} }

View File

@ -1,390 +1,383 @@
namespace Unosquare.RaspberryIO.Computer using System;
{ using System.Collections.Generic;
using System; using System.Globalization;
using System.Collections.Generic; using System.IO;
using System.Globalization; using System.Linq;
using System.IO; using System.Reflection;
using System.Linq;
using System.Reflection; using Swan;
using Abstractions; using Swan.DependencyInjection;
using Native;
using Swan; using Unosquare.RaspberryIO.Abstractions;
using Swan.DependencyInjection; using Unosquare.RaspberryIO.Native;
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// Retrieves the RaspberryPI System Information.
///
/// http://raspberry-pi-guide.readthedocs.io/en/latest/system.html.
/// </summary>
public sealed class SystemInfo : SingletonBase<SystemInfo> {
private const String CpuInfoFilePath = "/proc/cpuinfo";
private const String MemInfoFilePath = "/proc/meminfo";
private const String UptimeFilePath = "/proc/uptime";
private const Int32 NewStyleCodesMask = 0x800000;
private BoardModel _boardModel;
private ProcessorModel _processorModel;
private Manufacturer _manufacturer;
private MemorySize _memorySize;
/// <summary> /// <summary>
/// Retrieves the RaspberryPI System Information. /// Prevents a default instance of the <see cref="SystemInfo"/> class from being created.
///
/// http://raspberry-pi-guide.readthedocs.io/en/latest/system.html.
/// </summary> /// </summary>
public sealed class SystemInfo : SingletonBase<SystemInfo> /// <exception cref="NotSupportedException">Could not initialize the GPIO controller.</exception>
{ private SystemInfo() {
private const string CpuInfoFilePath = "/proc/cpuinfo"; #region Obtain and format a property dictionary
private const string MemInfoFilePath = "/proc/meminfo";
private const string UptimeFilePath = "/proc/uptime"; PropertyInfo[] properties = typeof(SystemInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(
p => p.CanWrite && p.CanRead && (p.PropertyType == typeof(String) || p.PropertyType == typeof(String[]))).ToArray();
private const int NewStyleCodesMask = 0x800000; Dictionary<String, PropertyInfo> propDictionary = new Dictionary<String, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
private BoardModel _boardModel; foreach(PropertyInfo prop in properties) {
private ProcessorModel _processorModel; propDictionary[prop.Name.Replace(" ", String.Empty).ToLowerInvariant().Trim()] = prop;
private Manufacturer _manufacturer; }
private MemorySize _memorySize;
#endregion
/// <summary>
/// Prevents a default instance of the <see cref="SystemInfo"/> class from being created. #region Extract CPU information
/// </summary>
/// <exception cref="NotSupportedException">Could not initialize the GPIO controller.</exception> if(File.Exists(CpuInfoFilePath)) {
private SystemInfo() String[] cpuInfoLines = File.ReadAllLines(CpuInfoFilePath);
{
#region Obtain and format a property dictionary foreach(String line in cpuInfoLines) {
String[] lineParts = line.Split(new[] { ':' }, 2);
var properties = if(lineParts.Length != 2) {
typeof(SystemInfo) continue;
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) }
.Where(
p => String propertyKey = lineParts[0].Trim().Replace(" ", String.Empty);
p.CanWrite && p.CanRead && String propertyStringValue = lineParts[1].Trim();
(p.PropertyType == typeof(string) || p.PropertyType == typeof(string[])))
.ToArray(); if(!propDictionary.ContainsKey(propertyKey)) {
var propDictionary = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase); continue;
}
foreach (var prop in properties)
{ PropertyInfo property = propDictionary[propertyKey];
propDictionary[prop.Name.Replace(" ", string.Empty).ToLowerInvariant().Trim()] = prop; if(property.PropertyType == typeof(String)) {
} property.SetValue(this, propertyStringValue);
} else if(property.PropertyType == typeof(String[])) {
#endregion String[] propertyArrayValue = propertyStringValue.Split(' ');
property.SetValue(this, propertyArrayValue);
#region Extract CPU information }
}
if (File.Exists(CpuInfoFilePath)) }
{
var cpuInfoLines = File.ReadAllLines(CpuInfoFilePath); #endregion
foreach (var line in cpuInfoLines) this.ExtractMemoryInfo();
{ this.ExtractBoardVersion();
var lineParts = line.Split(new[] { ':' }, 2); this.ExtractOS();
if (lineParts.Length != 2) }
continue;
/// <summary>
var propertyKey = lineParts[0].Trim().Replace(" ", string.Empty); /// Gets the library version.
var propertyStringValue = lineParts[1].Trim(); /// </summary>
public Version? LibraryVersion {
if (!propDictionary.ContainsKey(propertyKey)) continue; get; private set;
}
var property = propDictionary[propertyKey];
if (property.PropertyType == typeof(string)) /// <summary>
{ /// Gets the OS information.
property.SetValue(this, propertyStringValue); /// </summary>
} /// <value>
else if (property.PropertyType == typeof(string[])) /// The os information.
{ /// </value>
var propertyArrayValue = propertyStringValue.Split(' '); public OsInfo? OperatingSystem {
property.SetValue(this, propertyArrayValue); get; set;
} }
}
} /// <summary>
/// Gets the Raspberry Pi version.
#endregion /// </summary>
public PiVersion RaspberryPiVersion {
ExtractMemoryInfo(); get; set;
ExtractBoardVersion(); }
ExtractOS();
} /// <summary>
/// Gets the board revision (1 or 2).
/// <summary> /// </summary>
/// Gets the library version. /// <value>
/// </summary> /// The wiring pi board revision.
public Version LibraryVersion { get; private set; } /// </value>
public Int32 BoardRevision {
/// <summary> get; set;
/// Gets the OS information. }
/// </summary>
/// <value> /// <summary>
/// The os information. /// Gets the number of processor cores.
/// </value> /// </summary>
public OsInfo OperatingSystem { get; set; } public Int32 ProcessorCount => Int32.TryParse(this.Processor, out Int32 outIndex) ? outIndex + 1 : 0;
/// <summary> /// <summary>
/// Gets the Raspberry Pi version. /// Gets the installed ram in bytes.
/// </summary> /// </summary>
public PiVersion RaspberryPiVersion { get; set; } public Int32 InstalledRam {
get; private set;
/// <summary> }
/// Gets the board revision (1 or 2).
/// </summary> /// <summary>
/// <value> /// Gets a value indicating whether this CPU is little endian.
/// The wiring pi board revision. /// </summary>
/// </value> public Boolean IsLittleEndian => BitConverter.IsLittleEndian;
public int BoardRevision { get; set; }
/// <summary>
/// <summary> /// Gets the CPU model name.
/// Gets the number of processor cores. /// </summary>
/// </summary> public String? ModelName {
public int ProcessorCount => int.TryParse(Processor, out var outIndex) ? outIndex + 1 : 0; get; private set;
}
/// <summary>
/// Gets the installed ram in bytes. /// <summary>
/// </summary> /// Gets a list of supported CPU features.
public int InstalledRam { get; private set; } /// </summary>
public String[]? Features {
/// <summary> get; private set;
/// Gets a value indicating whether this CPU is little endian. }
/// </summary>
public bool IsLittleEndian => BitConverter.IsLittleEndian; /// <summary>
/// Gets the CPU implementer hex code.
/// <summary> /// </summary>
/// Gets the CPU model name. public String? CpuImplementer {
/// </summary> get; private set;
public string ModelName { get; private set; } }
/// <summary> /// <summary>
/// Gets a list of supported CPU features. /// Gets the CPU architecture code.
/// </summary> /// </summary>
public string[] Features { get; private set; } public String? CpuArchitecture {
get; private set;
/// <summary> }
/// Gets the CPU implementer hex code.
/// </summary> /// <summary>
public string CpuImplementer { get; private set; } /// Gets the CPU variant code.
/// </summary>
/// <summary> public String? CpuVariant {
/// Gets the CPU architecture code. get; private set;
/// </summary> }
public string CpuArchitecture { get; private set; }
/// <summary>
/// <summary> /// Gets the CPU part code.
/// Gets the CPU variant code. /// </summary>
/// </summary> public String? CpuPart {
public string CpuVariant { get; private set; } get; private set;
}
/// <summary>
/// Gets the CPU part code. /// <summary>
/// </summary> /// Gets the CPU revision code.
public string CpuPart { get; private set; } /// </summary>
public String? CpuRevision {
/// <summary> get; private set;
/// Gets the CPU revision code. }
/// </summary>
public string CpuRevision { get; private set; } /// <summary>
/// Gets the hardware model number.
/// <summary> /// </summary>
/// Gets the hardware model number. public String? Hardware {
/// </summary> get; private set;
public string Hardware { get; private set; } }
/// <summary> /// <summary>
/// Gets the hardware revision number. /// Gets the hardware revision number.
/// </summary> /// </summary>
public string Revision { get; private set; } public String? Revision {
get; private set;
/// <summary> }
/// Gets the revision number (accordingly to new-style revision codes).
/// </summary> /// <summary>
public int RevisionNumber { get; set; } /// Gets the revision number (accordingly to new-style revision codes).
/// </summary>
/// <summary> public Int32 RevisionNumber {
/// Gets the board model (accordingly to new-style revision codes). get; set;
/// </summary> }
/// /// <exception cref="InvalidOperationException">This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)}.</exception>
public BoardModel BoardModel => /// <summary>
NewStyleRevisionCodes ? /// Gets the board model (accordingly to new-style revision codes).
_boardModel : /// </summary>
throw new InvalidOperationException($"This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)} property instead."); /// /// <exception cref="InvalidOperationException">This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)}.</exception>
public BoardModel BoardModel => this.NewStyleRevisionCodes ? this._boardModel : throw new InvalidOperationException($"This board does not support new-style revision codes. Use {nameof(this.RaspberryPiVersion)} property instead.");
/// <summary>
/// Gets processor model (accordingly to new-style revision codes). /// <summary>
/// </summary> /// Gets processor model (accordingly to new-style revision codes).
/// /// <exception cref="InvalidOperationException">This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)}.</exception> /// </summary>
public ProcessorModel ProcessorModel => /// /// <exception cref="InvalidOperationException">This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)}.</exception>
NewStyleRevisionCodes ? public ProcessorModel ProcessorModel => this.NewStyleRevisionCodes ? this._processorModel : throw new InvalidOperationException($"This board does not support new-style revision codes. Use {nameof(this.RaspberryPiVersion)} property instead.");
_processorModel :
throw new InvalidOperationException($"This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)} property instead."); /// <summary>
/// Gets the manufacturer of the board (accordingly to new-style revision codes).
/// <summary> /// </summary>
/// Gets the manufacturer of the board (accordingly to new-style revision codes). /// <exception cref="InvalidOperationException">This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)}.</exception>
/// </summary> public Manufacturer Manufacturer => this.NewStyleRevisionCodes ? this._manufacturer : throw new InvalidOperationException($"This board does not support new-style revision codes. Use {nameof(this.RaspberryPiVersion)} property instead.");
/// <exception cref="InvalidOperationException">This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)}.</exception>
public Manufacturer Manufacturer => /// <summary>
NewStyleRevisionCodes ? /// Gets the size of the memory (accordingly to new-style revision codes).
_manufacturer : /// </summary>
throw new InvalidOperationException($"This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)} property instead."); /// <exception cref="InvalidOperationException">This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)}.</exception>
public MemorySize MemorySize => this.NewStyleRevisionCodes ? this._memorySize : throw new InvalidOperationException($"This board does not support new-style revision codes. Use {nameof(this.RaspberryPiVersion)} property instead.");
/// <summary>
/// Gets the size of the memory (accordingly to new-style revision codes). /// <summary>
/// </summary> /// Gets the serial number.
/// <exception cref="InvalidOperationException">This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)}.</exception> /// </summary>
public MemorySize MemorySize => public String? Serial {
NewStyleRevisionCodes ? get; private set;
_memorySize : }
throw new InvalidOperationException($"This board does not support new-style revision codes. Use {nameof(RaspberryPiVersion)} property instead.");
/// <summary>
/// <summary> /// Gets the system up-time (in seconds).
/// Gets the serial number. /// </summary>
/// </summary> public Double Uptime {
public string Serial { get; private set; } get {
try {
/// <summary> if(File.Exists(UptimeFilePath) == false) {
/// Gets the system up-time (in seconds). return 0;
/// </summary> }
public double Uptime
{ String[] parts = File.ReadAllText(UptimeFilePath).Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
get
{ if(parts.Length >= 1 && Single.TryParse(parts[0], out Single result)) {
try return result;
{ }
if (File.Exists(UptimeFilePath) == false) return 0; } catch {
var parts = File.ReadAllText(UptimeFilePath).Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); /* Ignore */
}
if (parts.Length >= 1 && float.TryParse(parts[0], out var result))
return result; return 0;
} }
catch }
{
/* Ignore */ /// <summary>
} /// Gets the uptime in TimeSpan.
/// </summary>
return 0; public TimeSpan UptimeTimeSpan => TimeSpan.FromSeconds(this.Uptime);
}
} /// <summary>
/// Indicates if the board uses the new-style revision codes.
/// <summary> /// </summary>
/// Gets the uptime in TimeSpan. private Boolean NewStyleRevisionCodes {
/// </summary> get; set;
public TimeSpan UptimeTimeSpan => TimeSpan.FromSeconds(Uptime); }
/// <summary> /// <summary>
/// Indicates if the board uses the new-style revision codes. /// Placeholder for processor index.
/// </summary> /// </summary>
private bool NewStyleRevisionCodes { get; set; } private String? Processor {
get; set;
/// <summary> }
/// Placeholder for processor index.
/// </summary> /// <summary>
private string Processor { get; set; } /// Returns a <see cref="String" /> that represents this instance.
/// </summary>
/// <summary> /// <returns>
/// Returns a <see cref="string" /> that represents this instance. /// A <see cref="String" /> that represents this instance.
/// </summary> /// </returns>
/// <returns> public override String ToString() {
/// A <see cref="string" /> that represents this instance. PropertyInfo[] properties = typeof(SystemInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(
/// </returns> p => p.CanRead && (p.PropertyType == typeof(String) || p.PropertyType == typeof(String[]) || p.PropertyType == typeof(Int32) || p.PropertyType == typeof(Boolean) || p.PropertyType == typeof(TimeSpan))).ToArray();
public override string ToString()
{ List<String> propertyValues2 = new List<String> {
var properties = typeof(SystemInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public) "System Information",
.Where(p => p.CanRead && ( $"\t{nameof(this.LibraryVersion),-22}: {this.LibraryVersion}",
p.PropertyType == typeof(string) || $"\t{nameof(this.RaspberryPiVersion),-22}: {this.RaspberryPiVersion}"
p.PropertyType == typeof(string[]) || };
p.PropertyType == typeof(int) ||
p.PropertyType == typeof(bool) || foreach(PropertyInfo property in properties) {
p.PropertyType == typeof(TimeSpan))) if(property.PropertyType != typeof(String[])) {
.ToArray(); propertyValues2.Add($"\t{property.Name,-22}: {property.GetValue(this)}");
} else if(property.GetValue(this) is String[] allValues) {
var propertyValues2 = new List<string> String concatValues = String.Join(" ", allValues);
{ propertyValues2.Add($"\t{property.Name,-22}: {concatValues}");
"System Information", }
$"\t{nameof(LibraryVersion),-22}: {LibraryVersion}", }
$"\t{nameof(RaspberryPiVersion),-22}: {RaspberryPiVersion}",
}; return String.Join(Environment.NewLine, propertyValues2.ToArray());
}
foreach (var property in properties)
{ private void ExtractOS() {
if (property.PropertyType != typeof(string[])) try {
{ _ = Standard.Uname(out SystemName unameInfo);
propertyValues2.Add($"\t{property.Name,-22}: {property.GetValue(this)}");
} this.OperatingSystem = new OsInfo {
else if (property.GetValue(this) is string[] allValues) DomainName = unameInfo.DomainName,
{ Machine = unameInfo.Machine,
var concatValues = string.Join(" ", allValues); NodeName = unameInfo.NodeName,
propertyValues2.Add($"\t{property.Name,-22}: {concatValues}"); Release = unameInfo.Release,
} SysName = unameInfo.SysName,
} Version = unameInfo.Version,
};
return string.Join(Environment.NewLine, propertyValues2.ToArray()); } catch {
} this.OperatingSystem = new OsInfo();
}
private void ExtractOS() }
{
try private void ExtractBoardVersion() {
{ Boolean hasSysInfo = DependencyContainer.Current.CanResolve<ISystemInfo>();
Standard.Uname(out var unameInfo);
try {
OperatingSystem = new OsInfo if(String.IsNullOrWhiteSpace(this.Revision) == false && Int32.TryParse(this.Revision != null ? this.Revision.ToUpperInvariant() : "", NumberStyles.HexNumber, CultureInfo.InvariantCulture, out Int32 boardVersion)) {
{ this.RaspberryPiVersion = PiVersion.Unknown;
DomainName = unameInfo.DomainName, if(Enum.IsDefined(typeof(PiVersion), boardVersion)) {
Machine = unameInfo.Machine, this.RaspberryPiVersion = (PiVersion)boardVersion;
NodeName = unameInfo.NodeName, }
Release = unameInfo.Release,
SysName = unameInfo.SysName, if((boardVersion & NewStyleCodesMask) == NewStyleCodesMask) {
Version = unameInfo.Version, this.NewStyleRevisionCodes = true;
}; this.RevisionNumber = boardVersion & 0xF;
} this._boardModel = (BoardModel)((boardVersion >> 4) & 0xFF);
catch this._processorModel = (ProcessorModel)((boardVersion >> 12) & 0xF);
{ this._manufacturer = (Manufacturer)((boardVersion >> 16) & 0xF);
OperatingSystem = new OsInfo(); this._memorySize = (MemorySize)((boardVersion >> 20) & 0x7);
} }
} }
private void ExtractBoardVersion() if(hasSysInfo) {
{ this.BoardRevision = (Int32)DependencyContainer.Current.Resolve<ISystemInfo>().BoardRevision;
var hasSysInfo = DependencyContainer.Current.CanResolve<ISystemInfo>(); }
} catch {
try /* Ignore */
{ }
if (string.IsNullOrWhiteSpace(Revision) == false &&
int.TryParse( if(hasSysInfo) {
Revision.ToUpperInvariant(), this.LibraryVersion = DependencyContainer.Current.Resolve<ISystemInfo>().LibraryVersion;
NumberStyles.HexNumber, }
CultureInfo.InvariantCulture, }
out var boardVersion))
{ private void ExtractMemoryInfo() {
RaspberryPiVersion = PiVersion.Unknown; if(!File.Exists(MemInfoFilePath)) {
if (Enum.IsDefined(typeof(PiVersion), boardVersion)) return;
RaspberryPiVersion = (PiVersion)boardVersion; }
if ((boardVersion & NewStyleCodesMask) == NewStyleCodesMask) String[] memInfoLines = File.ReadAllLines(MemInfoFilePath);
{
NewStyleRevisionCodes = true; foreach(String line in memInfoLines) {
RevisionNumber = boardVersion & 0xF; String[] lineParts = line.Split(new[] { ':' }, 2);
_boardModel = (BoardModel)((boardVersion >> 4) & 0xFF); if(lineParts.Length != 2) {
_processorModel = (ProcessorModel)((boardVersion >> 12) & 0xF); continue;
_manufacturer = (Manufacturer)((boardVersion >> 16) & 0xF); }
_memorySize = (MemorySize)((boardVersion >> 20) & 0x7);
} if(lineParts[0].ToLowerInvariant().Trim().Equals("memtotal") == false) {
} continue;
}
if (hasSysInfo)
BoardRevision = (int)DependencyContainer.Current.Resolve<ISystemInfo>().BoardRevision; String memKb = lineParts[1].ToLowerInvariant().Trim().Replace("kb", String.Empty).Trim();
}
catch if(!Int32.TryParse(memKb, out Int32 parsedMem)) {
{ continue;
/* Ignore */ }
}
this.InstalledRam = parsedMem * 1024;
if (hasSysInfo) break;
LibraryVersion = DependencyContainer.Current.Resolve<ISystemInfo>().LibraryVersion; }
} }
}
private void ExtractMemoryInfo()
{
if (!File.Exists(MemInfoFilePath)) return;
var memInfoLines = File.ReadAllLines(MemInfoFilePath);
foreach (var line in memInfoLines)
{
var lineParts = line.Split(new[] { ':' }, 2);
if (lineParts.Length != 2)
continue;
if (lineParts[0].ToLowerInvariant().Trim().Equals("memtotal") == false)
continue;
var memKb = lineParts[1].ToLowerInvariant().Trim().Replace("kb", string.Empty).Trim();
if (!int.TryParse(memKb, out var parsedMem)) continue;
InstalledRam = parsedMem * 1024;
break;
}
}
}
} }

View File

@ -1,23 +1,29 @@
namespace Unosquare.RaspberryIO.Computer using System;
{
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// Represents a wireless network information.
/// </summary>
public class WirelessNetworkInfo {
/// <summary> /// <summary>
/// Represents a wireless network information. /// Gets the ESSID of the Wireless network.
/// </summary> /// </summary>
public class WirelessNetworkInfo public String? Name {
{ get; internal set;
/// <summary> }
/// Gets the ESSID of the Wireless network.
/// </summary> /// <summary>
public string Name { get; internal set; } /// Gets the network quality.
/// </summary>
/// <summary> public String? Quality {
/// Gets the network quality. get; internal set;
/// </summary> }
public string Quality { get; internal set; }
/// <summary>
/// <summary> /// Gets a value indicating whether this instance is encrypted.
/// Gets a value indicating whether this instance is encrypted. /// </summary>
/// </summary> public Boolean IsEncrypted {
public bool IsEncrypted { get; internal set; } get; internal set;
} }
}
} }

View File

@ -1,17 +1,16 @@
namespace Unosquare.RaspberryIO.Native using System;
{ using System.Runtime.InteropServices;
using System.Runtime.InteropServices;
namespace Unosquare.RaspberryIO.Native {
internal static class Standard internal static class Standard {
{ internal const String LibCLibrary = "libc";
internal const string LibCLibrary = "libc";
/// <summary>
/// <summary> /// Fills in the structure with information about the system.
/// Fills in the structure with information about the system. /// </summary>
/// </summary> /// <param name="name">The name.</param>
/// <param name="name">The name.</param> /// <returns>The result.</returns>
/// <returns>The result.</returns> [DllImport(LibCLibrary, EntryPoint = "uname", SetLastError = true)]
[DllImport(LibCLibrary, EntryPoint = "uname", SetLastError = true)] public static extern Int32 Uname(out SystemName name);
public static extern int Uname(out SystemName name); }
}
} }

View File

@ -1,47 +1,46 @@
namespace Unosquare.RaspberryIO.Native using System;
{ using System.Runtime.InteropServices;
using System.Runtime.InteropServices;
namespace Unosquare.RaspberryIO.Native {
/// <summary>
/// OS uname structure.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SystemName {
/// <summary> /// <summary>
/// OS uname structure. /// System name.
/// </summary> /// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
public struct SystemName public String SysName;
{
/// <summary> /// <summary>
/// System name. /// Node name.
/// </summary> /// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
public string SysName; public String NodeName;
/// <summary> /// <summary>
/// Node name. /// Release level.
/// </summary> /// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
public string NodeName; public String Release;
/// <summary> /// <summary>
/// Release level. /// Version level.
/// </summary> /// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
public string Release; public String Version;
/// <summary> /// <summary>
/// Version level. /// Hardware level.
/// </summary> /// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
public string Version; public String Machine;
/// <summary> /// <summary>
/// Hardware level. /// Domain name.
/// </summary> /// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
public string Machine; public String DomainName;
}
/// <summary>
/// Domain name.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
public string DomainName;
}
} }

View File

@ -1,141 +1,138 @@
namespace Unosquare.RaspberryIO using System;
{ using System.Threading.Tasks;
using Abstractions;
using Camera; using Swan;
using Computer; using Swan.DependencyInjection;
using Swan;
using Swan.DependencyInjection; using Unosquare.RaspberryIO.Abstractions;
using System; using Unosquare.RaspberryIO.Camera;
using System.Threading.Tasks; using Unosquare.RaspberryIO.Computer;
namespace Unosquare.RaspberryIO {
/// <summary>
/// Our main character. Provides access to the Raspberry Pi's GPIO, system and board information and Camera.
/// </summary>
public static class Pi {
private const String MissingDependenciesMessage = "You need to load a valid assembly (WiringPi or PiGPIO).";
private static readonly Object SyncLock = new Object();
private static Boolean _isInit;
private static SystemInfo? _info;
/// <summary> /// <summary>
/// Our main character. Provides access to the Raspberry Pi's GPIO, system and board information and Camera. /// Initializes static members of the <see cref="Pi" /> class.
/// </summary> /// </summary>
public static class Pi static Pi() {
{ lock(SyncLock) {
private const string MissingDependenciesMessage = "You need to load a valid assembly (WiringPi or PiGPIO)."; Camera = CameraController.Instance;
private static readonly object SyncLock = new object(); PiDisplay = DsiDisplay.Instance;
private static bool _isInit; Audio = AudioSettings.Instance;
private static SystemInfo _info; Bluetooth = Bluetooth.Instance;
}
/// <summary> }
/// Initializes static members of the <see cref="Pi" /> class.
/// </summary> /// <summary>
static Pi() /// Provides information on this Raspberry Pi's CPU and form factor.
{ /// </summary>
lock (SyncLock) public static SystemInfo Info => _info ??= SystemInfo.Instance;
{
Camera = CameraController.Instance; /// <summary>
PiDisplay = DsiDisplay.Instance; /// Provides access to the Raspberry Pi's GPIO as a collection of GPIO Pins.
Audio = AudioSettings.Instance; /// </summary>
Bluetooth = Bluetooth.Instance; public static IGpioController Gpio => ResolveDependency<IGpioController>();
}
} /// <summary>
/// Provides access to the 2-channel SPI bus.
/// <summary> /// </summary>
/// Provides information on this Raspberry Pi's CPU and form factor. public static ISpiBus Spi => ResolveDependency<ISpiBus>();
/// </summary>
public static SystemInfo Info => _info ??= SystemInfo.Instance; /// <summary>
/// Provides access to the functionality of the i2c bus.
/// <summary> /// </summary>
/// Provides access to the Raspberry Pi's GPIO as a collection of GPIO Pins. public static II2CBus I2C => ResolveDependency<II2CBus>();
/// </summary>
public static IGpioController Gpio => /// <summary>
ResolveDependency<IGpioController>(); /// Provides access to timing functionality.
/// </summary>
/// <summary> public static ITiming Timing => ResolveDependency<ITiming>();
/// Provides access to the 2-channel SPI bus.
/// </summary> /// <summary>
public static ISpiBus Spi => /// Provides access to threading functionality.
ResolveDependency<ISpiBus>(); /// </summary>
public static IThreading Threading => ResolveDependency<IThreading>();
/// <summary>
/// Provides access to the functionality of the i2c bus. /// <summary>
/// </summary> /// Provides access to the official Raspberry Pi Camera.
public static II2CBus I2C => /// </summary>
ResolveDependency<II2CBus>(); public static CameraController Camera {
get;
/// <summary> }
/// Provides access to timing functionality.
/// </summary> /// <summary>
public static ITiming Timing => /// Provides access to the official Raspberry Pi 7-inch DSI Display.
ResolveDependency<ITiming>(); /// </summary>
public static DsiDisplay PiDisplay {
/// <summary> get;
/// Provides access to threading functionality. }
/// </summary>
public static IThreading Threading => /// <summary>
ResolveDependency<IThreading>(); /// Provides access to Raspberry Pi ALSA sound card driver.
/// </summary>
/// <summary> public static AudioSettings Audio {
/// Provides access to the official Raspberry Pi Camera. get;
/// </summary> }
public static CameraController Camera { get; }
/// <summary>
/// <summary> /// Provides access to Raspberry Pi Bluetooth driver.
/// Provides access to the official Raspberry Pi 7-inch DSI Display. /// </summary>
/// </summary> public static Bluetooth Bluetooth {
public static DsiDisplay PiDisplay { get; } get;
}
/// <summary>
/// Provides access to Raspberry Pi ALSA sound card driver. /// <summary>
/// </summary> /// Restarts the Pi. Must be running as SU.
public static AudioSettings Audio { get; } /// </summary>
/// <returns>The process result.</returns>
/// <summary> public static Task<ProcessResult> RestartAsync() => ProcessRunner.GetProcessResultAsync("reboot");
/// Provides access to Raspberry Pi Bluetooth driver.
/// </summary> /// <summary>
public static Bluetooth Bluetooth { get; } /// Restarts the Pi. Must be running as SU.
/// </summary>
/// <summary> /// <returns>The process result.</returns>
/// Restarts the Pi. Must be running as SU. public static ProcessResult Restart() => RestartAsync().GetAwaiter().GetResult();
/// </summary>
/// <returns>The process result.</returns> /// <summary>
public static Task<ProcessResult> RestartAsync() => ProcessRunner.GetProcessResultAsync("reboot"); /// Halts the Pi. Must be running as SU.
/// </summary>
/// <summary> /// <returns>The process result.</returns>
/// Restarts the Pi. Must be running as SU. public static Task<ProcessResult> ShutdownAsync() => ProcessRunner.GetProcessResultAsync("halt");
/// </summary>
/// <returns>The process result.</returns> /// <summary>
public static ProcessResult Restart() => RestartAsync().GetAwaiter().GetResult(); /// Halts the Pi. Must be running as SU.
/// </summary>
/// <summary> /// <returns>The process result.</returns>
/// Halts the Pi. Must be running as SU. public static ProcessResult Shutdown() => ShutdownAsync().GetAwaiter().GetResult();
/// </summary>
/// <returns>The process result.</returns> /// <summary>
public static Task<ProcessResult> ShutdownAsync() => ProcessRunner.GetProcessResultAsync("halt"); /// Initializes an Abstractions implementation.
/// </summary>
/// <summary> /// <typeparam name="T">An implementation of <see cref="IBootstrap"/>.</typeparam>
/// Halts the Pi. Must be running as SU. public static void Init<T>() where T : IBootstrap {
/// </summary> lock(SyncLock) {
/// <returns>The process result.</returns> if(_isInit) {
public static ProcessResult Shutdown() => ShutdownAsync().GetAwaiter().GetResult(); return;
}
/// <summary>
/// Initializes an Abstractions implementation. Activator.CreateInstance<T>().Bootstrap();
/// </summary> _isInit = true;
/// <typeparam name="T">An implementation of <see cref="IBootstrap"/>.</typeparam> }
public static void Init<T>() }
where T : IBootstrap
{ private static T ResolveDependency<T>() where T : class {
lock (SyncLock) if(!_isInit) {
{ throw new InvalidOperationException($"You must first initialize {nameof(Pi)} referencing a valid {nameof(IBootstrap)} implementation.");
if (_isInit) return; }
Activator.CreateInstance<T>().Bootstrap(); return DependencyContainer.Current.CanResolve<T>() ? DependencyContainer.Current.Resolve<T>() : throw new InvalidOperationException(MissingDependenciesMessage);
_isInit = true; }
} }
}
private static T ResolveDependency<T>()
where T : class
{
if (!_isInit)
throw new InvalidOperationException($"You must first initialize {nameof(Pi)} referencing a valid {nameof(IBootstrap)} implementation.");
return DependencyContainer.Current.CanResolve<T>()
? DependencyContainer.Current.Resolve<T>()
: throw new InvalidOperationException(MissingDependenciesMessage);
}
}
} }

View File

@ -16,6 +16,7 @@ This library enables developers to use the various Raspberry Pi's hardware modul
<PackageLicenseUrl>https://raw.githubusercontent.com/unosquare/raspberryio/master/LICENSE</PackageLicenseUrl> <PackageLicenseUrl>https://raw.githubusercontent.com/unosquare/raspberryio/master/LICENSE</PackageLicenseUrl>
<PackageTags>Raspberry Pi GPIO Camera SPI I2C Embedded IoT Mono C# .NET</PackageTags> <PackageTags>Raspberry Pi GPIO Camera SPI I2C Embedded IoT Mono C# .NET</PackageTags>
<LangVersion>8.0</LangVersion> <LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>