RaspberryIO/Unosquare.RaspberryIO/Computer/SystemInfo.cs
2019-12-03 18:43:54 +01:00

343 lines
10 KiB
C#

using Unosquare.RaspberryIO.Native;
using Unosquare.Swan.Abstractions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Unosquare.RaspberryIO.Computer {
/// <summary>
/// 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 static readonly StringComparer StringComparer = StringComparer.InvariantCultureIgnoreCase;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Codequalität", "IDE0052:Ungelesene private Member entfernen", Justification = "<Ausstehend>")]
private static readonly Object SyncRoot = new Object();
/// <summary>
/// Prevents a default instance of the <see cref="SystemInfo"/> class from being created.
/// </summary>
/// <exception cref="NotSupportedException">Could not initialize the GPIO controller</exception>
private SystemInfo() {
#region Obtain and format a property dictionary
PropertyInfo[] properties =
typeof(SystemInfo).GetTypeInfo()
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(
p =>
p.CanWrite && p.CanRead &&
(p.PropertyType == typeof(String) || p.PropertyType == typeof(String[])))
.ToArray();
Dictionary<String, PropertyInfo> propDictionary = new Dictionary<String, PropertyInfo>(StringComparer);
foreach(PropertyInfo prop in properties) {
propDictionary[prop.Name.Replace(" ", String.Empty).ToLowerInvariant().Trim()] = prop;
}
#endregion
#region Extract CPU information
if(File.Exists(CpuInfoFilePath)) {
String[] cpuInfoLines = File.ReadAllLines(CpuInfoFilePath);
foreach(String line in cpuInfoLines) {
String[] lineParts = line.Split(new[] { ':' }, 2);
if(lineParts.Length != 2) {
continue;
}
String propertyKey = lineParts[0].Trim().Replace(" ", String.Empty);
String propertyStringValue = lineParts[1].Trim();
if(!propDictionary.ContainsKey(propertyKey)) {
continue;
}
PropertyInfo property = propDictionary[propertyKey];
if(property.PropertyType == typeof(String)) {
property.SetValue(this, propertyStringValue);
} else if(property.PropertyType == typeof(String[])) {
String[] propertyArrayAvalue = propertyStringValue.Split(' ');
property.SetValue(this, propertyArrayAvalue);
}
}
}
#endregion
#region Extract Memory Information
if(File.Exists(MemInfoFilePath)) {
String[] memInfoLines = File.ReadAllLines(MemInfoFilePath);
foreach(String line in memInfoLines) {
String[] lineParts = line.Split(new[] { ':' }, 2);
if(lineParts.Length != 2) {
continue;
}
if(lineParts[0].ToLowerInvariant().Trim().Equals("memtotal") == false) {
continue;
}
String memKb = lineParts[1].ToLowerInvariant().Trim().Replace("kb", String.Empty).Trim();
if(Int32.TryParse(memKb, out Int32 parsedMem)) {
this.InstalledRam = parsedMem * 1024;
break;
}
}
}
#endregion
#region Board Version and Form Factor
try {
if(String.IsNullOrWhiteSpace(this.Revision) == false &&
Int32.TryParse(
this.Revision.ToUpperInvariant(),
NumberStyles.HexNumber,
CultureInfo.InvariantCulture,
out Int32 boardVersion)) {
this.RaspberryPiVersion = PiVersion.Unknown;
if(Enum.GetValues(typeof(PiVersion)).Cast<Int32>().Contains(boardVersion)) {
this.RaspberryPiVersion = (PiVersion)boardVersion;
}
}
this.WiringPiBoardRevision = WiringPi.PiBoardRev();
} catch {
/* Ignore */
}
#endregion
#region Version Information
{
String[] libParts = WiringPi.WiringPiLibrary.Split('.');
Int32 major = Int32.Parse(libParts[libParts.Length - 2]);
Int32 minor = Int32.Parse(libParts[libParts.Length - 1]);
Version version = new Version(major, minor);
this.WiringPiVersion = version;
}
#endregion
#region Extract OS Info
try {
_ = Standard.Uname(out SystemName unameInfo);
this.OperatingSystem = new OsInfo {
DomainName = unameInfo.DomainName,
Machine = unameInfo.Machine,
NodeName = unameInfo.NodeName,
Release = unameInfo.Release,
SysName = unameInfo.SysName,
Version = unameInfo.Version
};
} catch {
this.OperatingSystem = new OsInfo();
}
#endregion
}
/// <summary>
/// Gets the wiring pi library version.
/// </summary>
public Version WiringPiVersion {
get;
}
/// <summary>
/// Gets the OS information.
/// </summary>
/// <value>
/// The os information.
/// </value>
public OsInfo OperatingSystem {
get;
}
/// <summary>
/// Gets the Raspberry Pi version.
/// </summary>
public PiVersion RaspberryPiVersion {
get;
}
/// <summary>
/// Gets the Wiring Pi board revision (1 or 2).
/// </summary>
/// <value>
/// The wiring pi board revision.
/// </value>
public Int32 WiringPiBoardRevision {
get;
}
/// <summary>
/// Gets the number of processor cores.
/// </summary>
public Int32 ProcessorCount => Int32.TryParse(this.Processor, out Int32 outIndex) ? outIndex + 1 : 0;
/// <summary>
/// Gets the installed ram in bytes.
/// </summary>
public Int32 InstalledRam {
get;
}
/// <summary>
/// Gets a value indicating whether this CPU is little endian.
/// </summary>
public Boolean IsLittleEndian => BitConverter.IsLittleEndian;
/// <summary>
/// Gets the CPU model name.
/// </summary>
public String ModelName {
get; private set;
}
/// <summary>
/// Gets a list of supported CPU features.
/// </summary>
public String[] Features {
get; private set;
}
/// <summary>
/// Gets the CPU implementer hex code.
/// </summary>
public String CpuImplementer {
get; private set;
}
/// <summary>
/// Gets the CPU architecture code.
/// </summary>
public String CpuArchitecture {
get; private set;
}
/// <summary>
/// Gets the CPU variant code.
/// </summary>
public String CpuVariant {
get; private set;
}
/// <summary>
/// Gets the CPU part code.
/// </summary>
public String CpuPart {
get; private set;
}
/// <summary>
/// Gets the CPU revision code.
/// </summary>
public String CpuRevision {
get; private set;
}
/// <summary>
/// Gets the hardware model number.
/// </summary>
public String Hardware {
get; private set;
}
/// <summary>
/// Gets the hardware revision number.
/// </summary>
public String Revision {
get; private set;
}
/// <summary>
/// Gets the serial number.
/// </summary>
public String Serial {
get; private set;
}
/// <summary>
/// Gets the system uptime (in seconds).
/// </summary>
public Double Uptime {
get {
try {
if(File.Exists(UptimeFilePath) == false) {
return 0;
}
String[] parts = File.ReadAllText(UptimeFilePath).Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if(parts.Length >= 1 && Single.TryParse(parts[0], out Single result)) {
return result;
}
} catch {
/* Ignore */
}
return 0;
}
}
/// <summary>
/// Gets the uptime in TimeSpan.
/// </summary>
public TimeSpan UptimeTimeSpan => TimeSpan.FromSeconds(this.Uptime);
/// <summary>
/// Placeholder for processor index
/// </summary>
private String Processor {
get; set;
}
/// <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() {
PropertyInfo[] properties = typeof(SystemInfo).GetTypeInfo().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.CanRead && (
p.PropertyType == typeof(String) ||
p.PropertyType == typeof(String[]) ||
p.PropertyType == typeof(Int32) ||
p.PropertyType == typeof(Boolean) ||
p.PropertyType == typeof(TimeSpan)))
.ToArray();
List<String> properyValues = new List<String>
{
"System Information",
$"\t{nameof(this.WiringPiVersion),-22}: {this.WiringPiVersion}",
$"\t{nameof(this.RaspberryPiVersion),-22}: {this.RaspberryPiVersion}"
};
foreach(PropertyInfo property in properties) {
if(property.PropertyType != typeof(String[])) {
properyValues.Add($"\t{property.Name,-22}: {property.GetValue(this)}");
} else if(property.GetValue(this) is String[] allValues) {
String concatValues = String.Join(" ", allValues);
properyValues.Add($"\t{property.Name,-22}: {concatValues}");
}
}
return String.Join(Environment.NewLine, properyValues.ToArray());
}
}
}