Common console cleaned

This commit is contained in:
Stoyan Zlatev 2023-09-14 10:44:31 +02:00
parent 64d4709240
commit d6ae9cdb8c
12 changed files with 0 additions and 1088 deletions

View File

@ -1,117 +0,0 @@
namespace CommonConsole
{
using System;
using System.Linq;
using System.Text;
public static class BitExtensions
{
public static byte[] GetBits(this byte[] bytes)
{
if (bytes is null)
{
return Array.Empty<byte>();
}
var bytesCount = bytes.Length;
var bitsCount = bytesCount * 8;
var bits = new byte[bitsCount];
var bit = 0;
foreach (var @byte in bytes)
{
for (int b = 7; b >= 0; b--)
{
bits[bit++] = (byte)((@byte >> b) % 2);
}
}
return bits;
}
public static byte[] GetBytes(this byte value, int take = 1)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this sbyte value, int take = 2)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this short value, int take = 2)
=> BitConverter.GetBytes(value).Take(2);
public static byte[] GetBytes(this ushort value, int take = 2)
=> BitConverter.GetBytes(value).Take(2);
public static byte[] GetBytes(this int value, int take = 4)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this uint value, int take = 4)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this long value, int take = 8)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this ulong value, int take = 8)
=> BitConverter.GetBytes(value).Take(take);
public static byte[] GetBytes(this double value)
=> BitConverter.GetBytes(value);
public static byte[] GetBytes(this string value)
=> Encoding.ASCII.GetBytes(value);
public static byte[] Swap(this byte[] bytes)
{
if (bytes is null)
{
return Array.Empty<byte>();
}
var length = bytes.Length;
var swapped = new byte[length];
for (int x = 0; x < length; x++)
{
swapped[x] = bytes[length - x - 1];
}
return swapped;
}
public static byte[] Take(this byte[] bytesSRC, int count)
{
if (bytesSRC is null || count < 0)
{
return Array.Empty<byte>();
}
var bytesDST = new byte[count];
Array.Copy(bytesSRC, 0, bytesDST, 0, count);
return bytesDST;
}
public static string ToHex(this byte[] value, string separator = " ")
{
if (value is null)
{
return string.Empty;
}
return BitConverter.ToString(value).Replace("-", separator);
}
public static byte[] FromHex(this string value, string separator = " ")
{
if (string.IsNullOrWhiteSpace(value))
{
return Array.Empty<byte>();
}
return value
.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => byte.TryParse(x, out byte b) ? b : default(byte))
.ToArray();
}
}
}

View File

@ -46,18 +46,8 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BitExtensions.cs" />
<Compile Include="ConfigurationJson.cs" />
<Compile Include="JsonConverters\CurrentConverter.cs" />
<Compile Include="JsonConverters\FlowConverter.cs" />
<Compile Include="JsonConverters\PressureConverter.cs" />
<Compile Include="JsonConverters\TemperatureConverter.cs" />
<Compile Include="JsonConverters\TimeConverter.cs" />
<Compile Include="JsonConverters\VolumeConverter.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Unit.cs" />
<Compile Include="Value.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />

View File

@ -1,330 +0,0 @@
namespace CommonConsole
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
public class ConfigurationJson : Dictionary<string, Section>
{
public Section this[byte id]
=> this.Values.FirstOrDefault(x => x.Id == id)
?? new Section();
public new Section this[string key]
{
get
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("Section name should not be null or white space!");
}
if (!this.TryGetValue(key, out var section))
{
section = new Section();
this[key] = section;
}
return section;
}
set
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("Section name should not be null or white space!");
}
this[key] = value;
}
}
[OnDeserialized]
internal void OnDeserialized(StreamingContext _)
{
foreach (var kvp in this)
{
kvp.Value.Name = kvp.Key;
}
}
}
public class Section
{
public byte Id { get; set; }
[JsonIgnore]
public string Name { get; internal set; }
public Version Version { get; set; }
public Registers Registers { get; set; }
public Status Status { get; set; }
public Register this[string key]
{
get
{
if (this.Registers is null)
{
return new Register();
}
return this.Registers[key];
}
set
{
if (this.Registers != null)
{
this.Registers[key] = value;
}
}
}
public Register this[byte id]
=> this.Registers?[id] ?? new Register();
}
public class Version
{
public int? First { get; set; }
public int? Last { get; set; }
public bool InVersion(int version)
{
if (this.First is null && this.Last is null)
{
return false;
}
return (this.First ?? int.MinValue) <= version && (this.First ?? int.MaxValue) >= version;
}
}
public class Registers : Dictionary<string, Register>
{
public Register this[byte id]
=> this.Values.FirstOrDefault(x => x.Id == id)
?? new Register();
public new Register this[string key]
{
get
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("Register name should not be null or white space!");
}
if (!this.TryGetValue(key, out var register))
{
register = new Register();
this[key] = register;
}
return register;
}
set
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("Register name should not be null or white space!");
}
this[key] = value;
}
}
[OnDeserialized]
internal void OnDeserialized(StreamingContext _)
{
foreach (var kvp in this)
{
kvp.Value.Name = kvp.Key;
}
}
}
public class Register
{
public byte Id { get; set; }
[JsonIgnore]
public string Name { get; internal set; }
public Details Details { get; set; }
public Detail this[int version]
=> this.Details?[version] ?? new Detail();
}
public class Details : List<Detail>
{
public new Detail this[int version]
=> this.FirstOrDefault(x => x.Version?.InVersion(version) ?? false)
?? new Detail();
}
public class Detail
{
public string Type { get; set; }
public string StaticType { get; set; }
public Privilege Privilege { get; set; }
public Version Version { get; set; }
public Values Values { get; set; }
[JsonIgnore]
public Value Value { get; set; }
[JsonIgnore]
public Unit Unit { get; set; }
public object this[string property]
{
get
{
if (property == nameof(Value))
{
return this.Value?.Current;
}
else if (property == nameof(Unit))
{
return this.Unit?.Base;
}
return null;
}
set
{
if (property == nameof(Value) && this.Value != null)
{
this.Value.Current = value;
}
else if (property == nameof(Unit) && this.Unit != null)
{
this.Unit.Base = value;
}
}
}
[OnDeserialized]
internal void OnDeserialized(StreamingContext _)
{
try
{
var valueType = System.Type.GetType(
typeName: $"CommonConsole.{this.Type}",
throwOnError: false,
ignoreCase: true);
var instance = Activator.CreateInstance(valueType);
if (instance is Value value)
{
if (this.Values != null)
{
value.Current = this.Values.Default;
}
this.Value = value;
}
}
catch (Exception e)
{
// TODO: Handle exceptions.
}
}
}
public class Values
{
public object Default { get; set; }
public object Minimum { get; set; }
public object Maximum { get; set; }
}
public class Privilege
{
public Access Lvl1 { get; set; }
public Access Lvl2 { get; set; }
public Access Lvl3 { get; set; }
public Access Lvl4 { get; set; }
public Access Lvl5 { get; set; }
public Access Lvl6 { get; set; }
public Access Lvl7 { get; set; }
public Access Lvl8 { get; set; }
}
public enum Access : byte
{
NS,
NA,
RO,
WO,
RW
}
public class Status : Dictionary<string, StatusInfo>
{
}
public class StatusInfo
{
public byte Id { get; set; }
public string Action { get; set; }
public string Description { get; set; }
}
public class AccessConverter : JsonConverter
{
public override bool CanConvert(Type type)
=> type == typeof(Access)
|| type == typeof(Access?);
public override object ReadJson(JsonReader reader, Type _, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
var value = serializer.Deserialize<string>(reader);
if (Enum.TryParse(value, true, out Access access))
{
return access;
}
return default(Access);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer _1)
{
if (value != null)
{
writer.WriteValue($"{value}");
}
}
}
}

View File

@ -1,27 +0,0 @@
namespace CommonConsole.JsonConverters
{
using Newtonsoft.Json;
using System;
public class CurrentConverter : JsonConverter<Current>
{
public override Current ReadJson(JsonReader reader, Type objectType, Current existingValue, bool hasExistingValue, JsonSerializer serializer)
{
while (reader.ValueType != typeof(double))
{
reader.Read();
}
if (reader.Value is double value)
{
return value;
}
return existingValue;
}
public override void WriteJson(JsonWriter writer, Current value, JsonSerializer serializer)
=> writer.WriteValue((double)value);
}
}

View File

@ -1,27 +0,0 @@
namespace CommonConsole.JsonConverters
{
using Newtonsoft.Json;
using System;
public class FlowConverter : JsonConverter<Flow>
{
public override Flow ReadJson(JsonReader reader, Type objectType, Flow existingValue, bool hasExistingValue, JsonSerializer serializer)
{
while (reader.ValueType != typeof(double))
{
reader.Read();
}
if (reader.Value is double value)
{
return value;
}
return existingValue;
}
public override void WriteJson(JsonWriter writer, Flow value, JsonSerializer serializer)
=> writer.WriteValue((double)value);
}
}

View File

@ -1,27 +0,0 @@
namespace CommonConsole.JsonConverters
{
using Newtonsoft.Json;
using System;
public class PressureConverter : JsonConverter<Pressure>
{
public override Pressure ReadJson(JsonReader reader, Type objectType, Pressure existingValue, bool hasExistingValue, JsonSerializer serializer)
{
while (reader.ValueType != typeof(double))
{
reader.Read();
}
if (reader.Value is double value)
{
return value;
}
return existingValue;
}
public override void WriteJson(JsonWriter writer, Pressure value, JsonSerializer serializer)
=> writer.WriteValue((double)value);
}
}

View File

@ -1,27 +0,0 @@
namespace CommonConsole.JsonConverters
{
using Newtonsoft.Json;
using System;
public class TemperatureConverter : JsonConverter<Temperature>
{
public override Temperature ReadJson(JsonReader reader, Type objectType, Temperature existingValue, bool hasExistingValue, JsonSerializer serializer)
{
while (reader.ValueType != typeof(double))
{
reader.Read();
}
if (reader.Value is double value)
{
return value;
}
return existingValue;
}
public override void WriteJson(JsonWriter writer, Temperature value, JsonSerializer serializer)
=> writer.WriteValue((double)value);
}
}

View File

@ -1,27 +0,0 @@
namespace CommonConsole.JsonConverters
{
using Newtonsoft.Json;
using System;
public class TimeConverter : JsonConverter<Time>
{
public override Time ReadJson(JsonReader reader, Type objectType, Time existingValue, bool hasExistingValue, JsonSerializer serializer)
{
while (reader.ValueType != typeof(double))
{
reader.Read();
}
if (reader.Value is double value)
{
return value;
}
return existingValue;
}
public override void WriteJson(JsonWriter writer, Time value, JsonSerializer serializer)
=> writer.WriteValue((double)value);
}
}

View File

@ -1,27 +0,0 @@
namespace CommonConsole.JsonConverters
{
using Newtonsoft.Json;
using System;
public class VolumeConverter : JsonConverter<Volume>
{
public override Volume ReadJson(JsonReader reader, Type objectType, Volume existingValue, bool hasExistingValue, JsonSerializer serializer)
{
while (reader.ValueType != typeof(double))
{
reader.Read();
}
if (reader.Value is double value)
{
return value;
}
return existingValue;
}
public override void WriteJson(JsonWriter writer, Volume value, JsonSerializer serializer)
=> writer.WriteValue((double)value);
}
}

View File

@ -1,72 +1,9 @@
namespace CommonConsole
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Globalization;
using System.IO;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
var content = File.ReadAllText("../../configuration.json");
var configuration = JsonConvert.DeserializeObject<ConfigurationJson>(content);
byte sectionId = 10;
byte registerId = 2;
int version = 20;
/// Getting application section from the configuration
var sectionById = configuration[sectionId];
if (!string.IsNullOrWhiteSpace(sectionById.Name))
{
/// ??? When requested by name creates new Section if name not exists in the keys collection.
var sectionByName = configuration[sectionById.Name];
}
/// Geting register by sectionId and registerId
var registerById = configuration[sectionId][registerId];
if (!string.IsNullOrWhiteSpace(registerById.Name))
{
/// ??? When requested by name creates new Register for the section if name not exists in the keys collection.
var registerByName = configuration[sectionId][registerById.Name];
}
configuration[sectionId][registerId][version].Unit = Unit.MessurementUnits.FirstOrDefault() ?? nameof(Volume);
var unit = configuration[sectionId][registerId][version][nameof(Unit)];
if (unit is null)
{
configuration[sectionId][registerId][version][nameof(Unit)] = 1000;
}
configuration[sectionId][registerId][version].Value = Value.ValueTypes.FirstOrDefault() ?? nameof(int32_t);
var value = configuration[sectionId][registerId][version][nameof(Value)];
if (value is null)
{
configuration[sectionId][registerId][version][nameof(Value)] = 1000;
}
}
private static JsonSerializerSettings settings => new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new AccessConverter(),
new IsoDateTimeConverter
{
DateTimeStyles = DateTimeStyles.AssumeUniversal
}
},
};
}
}

View File

@ -1,223 +0,0 @@
namespace CommonConsole
{
using CommonConsole.JsonConverters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
public abstract class Unit
{
public const int MsInSec = 1000;
public const int SecInMin = 60;
public const int MinInH = 60;
public const int HInDay = 24;
public const int MlInL = 1000;
public const int LInm3 = 1000;
public const int PInBar = 100000;
public const int MAInH = 1000;
protected double value;
public virtual object Base { get; set; }
public override string ToString()
=> this.value.ToString();
public override bool Equals(object obj)
=> this.value.Equals(obj);
public override int GetHashCode()
=> this.value.GetHashCode();
public static implicit operator double (Unit @base)
=> @base?.value ?? default(double);
public static implicit operator double? (Unit @base)
=> @base?.value;
public static implicit operator Unit(string unitName)
{
try
{
var valueType = Type.GetType(
typeName: $"CommonConsole.{unitName}",
throwOnError: false,
ignoreCase: true);
var instance = Activator.CreateInstance(valueType);
if (instance is Unit unit)
{
return unit;
}
}
catch (Exception e)
{
// TODO: Handle exceptions.
}
return default(Unit);
}
public static IEnumerable<string> MessurementUnits
=> typeof(Unit)
.Assembly
.GetTypes()
.Where(x => typeof(Unit).IsAssignableFrom(x) && !x.IsAbstract)
.Select(x => x.Name);
}
[JsonConverter(typeof(CurrentConverter))]
public class Current : Unit
{
public double MiliampereHours
{
get => this.AmpereHours * MAInH;
set => this.AmpereHours = value / MAInH;
}
public double AmpereHours
{
get => this.value;
set => this.value = value;
}
public static implicit operator Current(double x)
=> new Current { value = x };
public static implicit operator Current(double? x)
=> new Current { value = x ?? 0 };
}
[JsonConverter(typeof(FlowConverter))]
public class Flow : Unit
{
public double CubicMeterInHour
{
get => this.value;
set => this.value = value;
}
public double LiterInMinute
{
get => this.CubicMeterInHour / MinInH * LInm3;
set => this.CubicMeterInHour = value * MinInH / LInm3;
}
public static implicit operator Flow(double x)
=> new Flow { value = x };
public static implicit operator Flow(double? x)
=> new Flow { value = x ?? 0 };
}
[JsonConverter(typeof(PressureConverter))]
public class Pressure : Unit
{
public double Pascal
{
get => this.value;
set => this.value = value;
}
public double Bar
{
get => this.Pascal / PInBar;
set => this.Pascal = value * PInBar;
}
public static implicit operator Pressure(double x)
=> new Pressure { value = x };
public static implicit operator Pressure(double? x)
=> new Pressure { value = x ?? 0 };
}
[JsonConverter(typeof(TemperatureConverter))]
public class Temperature : Unit
{
public double Celsius
{
get => this.value;
set => this.value = value;
}
public static implicit operator Temperature(double x)
=> new Temperature { value = x };
public static implicit operator Temperature(double? x)
=> new Temperature { value = x ?? 0 };
}
[JsonConverter(typeof(TimeConverter))]
public class Time : Unit
{
public double Miliseconds
{
get => this.Seconds * MsInSec;
set => this.Seconds = value / MsInSec;
}
public double Seconds
{
get => this.value;
set => this.value = value;
}
public double Minutes
{
get => this.Seconds / SecInMin;
set => this.Seconds = value * SecInMin;
}
public double Hours
{
get => this.Minutes / MinInH;
set => this.Minutes = value * MinInH;
}
public double Days
{
get => this.Hours / HInDay;
set => this.Hours = value * HInDay;
}
public static implicit operator Time(double x)
=> new Time { value = x };
public static implicit operator Time(double? x)
=> new Time { value = x ?? 0 };
}
[JsonConverter(typeof(VolumeConverter))]
public class Volume : Unit
{
public double Mililiter
{
get => this.Liter * MlInL;
set => this.Liter = value / MlInL;
}
public double Liter
{
get => this.value * LInm3;
set => this.value = value / LInm3;
}
public double CubicMeter
{
get => this.value * this.Factor;
set => this.value = value / this.Factor;
}
public int Factor { get; set; } = 1000;
public static implicit operator Volume(double x)
=> new Volume { value = x };
public static implicit operator Volume(double? x)
=> new Volume { value = x ?? 0 };
}
}

View File

@ -1,183 +0,0 @@
namespace CommonConsole
{
using System;
using System.Collections.Generic;
using System.Linq;
public abstract class Value
{
public virtual object Current { get; set; }
public virtual byte[] Buffer { get; set; }
public static implicit operator Value(string valueName)
{
try
{
var valueType = Type.GetType(
typeName: $"CommonConsole.{valueName}",
throwOnError: false,
ignoreCase: true);
var instance = Activator.CreateInstance(valueType);
if (instance is Value value)
{
return value;
}
}
catch (Exception e)
{
// TODO: Handle exceptions.
}
return default(Value);
}
public static IEnumerable<string> ValueTypes
=> typeof(Value)
.Assembly
.GetTypes()
.Where(x => typeof(Value).IsAssignableFrom(x) && !x.IsAbstract)
.Select(x => x.Name);
}
public class Value<T> : Value
{
protected T value;
}
public class bool_t : Value<bool>
{
public override object Current
{
get => this.value;
set => this.value = (bool)value;
}
}
public class rpc : Value<int>
{
public override object Current
{
get => this.value;
set => this.value = (int)value;
}
}
public class @string : Value<string>
{
public override object Current
{
get => this.value;
set => this.value = (string)value;
}
}
public class time_t : Value<int>
{
public override object Current
{
get => this.value;
set => this.value = (int)value;
}
}
public class status_t : Value<byte>
{
public override object Current
{
get => this.value;
set => this.value = (byte)value;
}
}
public class enum8 : Value<byte>
{
public override object Current
{
get => this.value;
set => this.value = (byte)value;
}
}
public class uint8_t : Value<byte>
{
public override object Current
{
get => this.value;
set => this.value = (byte)value;
}
}
public class uint16_t : Value<ushort>
{
public override object Current
{
get => this.value;
set => this.value = (ushort)value;
}
}
public class uint32_t : Value<uint>
{
public override object Current
{
get => this.value;
set => this.value = (uint)value;
}
}
public class uint64_t : Value<ulong>
{
public override object Current
{
get => this.value;
set => this.value = (ulong)value;
}
}
public class uint96_t : Value<string>
{
public override object Current
{
get => this.value;
set => this.value = (string)value;
}
}
public class int8_t : Value<sbyte>
{
public override object Current
{
get => this.value;
set => this.value = (sbyte)value;
}
}
public class int16_t : Value<short>
{
public override object Current
{
get => this.value;
set => this.value = (short)value;
}
}
public class int32_t : Value<int>
{
public override object Current
{
get => this.value;
set => this.value = (int)value;
}
}
public class int64_t : Value<long>
{
public override object Current
{
get => this.value;
set => this.value = (long)value;
}
}
}