From 65059f66edc7bc8969da4a77d9bdd1cde2100e0f Mon Sep 17 00:00:00 2001 From: glax Date: Thu, 1 Feb 2024 23:03:28 +0100 Subject: [PATCH] Rewrite Hierachy that shockers now contain the api they use. --- CShocker.sln.DotSettings.user | 5 ++ CShocker/CShocker.csproj | 2 +- CShocker/Devices/{ => APIs}/OpenShockHttp.cs | 6 +- .../Devices/{ => APIs}/OpenShockSerial.cs | 16 +++-- CShocker/Devices/{ => APIs}/PiShockHttp.cs | 6 +- CShocker/Devices/{ => APIs}/PiShockSerial.cs | 6 +- .../Devices/Abstract/{Device.cs => Api.cs} | 16 ++--- .../{OpenShockDevice.cs => OpenShockApi.cs} | 47 +++++++++----- CShocker/Devices/Abstract/PiShockApi.cs | 12 ++++ CShocker/Devices/Abstract/PiShockDevice.cs | 12 ---- ...ceJsonConverter.cs => ApiJsonConverter.cs} | 5 +- CShocker/Shockers/Abstract/Shocker.cs | 23 ++++++- .../Additional/ShockerJsonConverter.cs | 31 ++++----- CShocker/Shockers/OpenShockShocker.cs | 15 ++++- CShocker/Shockers/PiShockShocker.cs | 12 +++- TestApp/Logger.cs | 65 ------------------- TestApp/Program.cs | 54 +++++++-------- TestApp/TestApp.csproj | 6 ++ 18 files changed, 171 insertions(+), 168 deletions(-) create mode 100644 CShocker.sln.DotSettings.user rename CShocker/Devices/{ => APIs}/OpenShockHttp.cs (95%) rename CShocker/Devices/{ => APIs}/OpenShockSerial.cs (84%) rename CShocker/Devices/{ => APIs}/PiShockHttp.cs (95%) rename CShocker/Devices/{ => APIs}/PiShockSerial.cs (92%) rename CShocker/Devices/Abstract/{Device.cs => Api.cs} (82%) rename CShocker/Devices/Abstract/{OpenShockDevice.cs => OpenShockApi.cs} (54%) create mode 100644 CShocker/Devices/Abstract/PiShockApi.cs delete mode 100644 CShocker/Devices/Abstract/PiShockDevice.cs rename CShocker/Devices/Additional/{DeviceJsonConverter.cs => ApiJsonConverter.cs} (95%) delete mode 100644 TestApp/Logger.cs diff --git a/CShocker.sln.DotSettings.user b/CShocker.sln.DotSettings.user new file mode 100644 index 0000000..0f66c07 --- /dev/null +++ b/CShocker.sln.DotSettings.user @@ -0,0 +1,5 @@ + + True + <AssemblyExplorer> + <Assembly Path="C:\Users\Glax\RiderProjects\GlaxLogger\GlaxLogger\bin\Debug\net7.0\GlaxLogger.dll" /> +</AssemblyExplorer> \ No newline at end of file diff --git a/CShocker/CShocker.csproj b/CShocker/CShocker.csproj index 97dca06..7883af4 100644 --- a/CShocker/CShocker.csproj +++ b/CShocker/CShocker.csproj @@ -7,7 +7,7 @@ Glax https://github.com/C9Glax/CShocker git - 2.0.2 + 2.1.0 diff --git a/CShocker/Devices/OpenShockHttp.cs b/CShocker/Devices/APIs/OpenShockHttp.cs similarity index 95% rename from CShocker/Devices/OpenShockHttp.cs rename to CShocker/Devices/APIs/OpenShockHttp.cs index 1537be3..ea73984 100644 --- a/CShocker/Devices/OpenShockHttp.cs +++ b/CShocker/Devices/APIs/OpenShockHttp.cs @@ -7,13 +7,13 @@ using CShocker.Shockers; using CShocker.Shockers.Abstract; using Microsoft.Extensions.Logging; -namespace CShocker.Devices; +namespace CShocker.Devices.APIs; -public class OpenShockHttp : OpenShockDevice +public class OpenShockHttp : OpenShockApi { - protected override void ControlInternal(ControlAction action, IShocker shocker, int intensity, int duration) + protected override void ControlInternal(ControlAction action, Shocker shocker, int intensity, int duration) { if (shocker is not OpenShockShocker openShockShocker) { diff --git a/CShocker/Devices/OpenShockSerial.cs b/CShocker/Devices/APIs/OpenShockSerial.cs similarity index 84% rename from CShocker/Devices/OpenShockSerial.cs rename to CShocker/Devices/APIs/OpenShockSerial.cs index 8e1dad9..91dbfb7 100644 --- a/CShocker/Devices/OpenShockSerial.cs +++ b/CShocker/Devices/APIs/OpenShockSerial.cs @@ -6,9 +6,9 @@ using CShocker.Shockers; using CShocker.Shockers.Abstract; using Microsoft.Extensions.Logging; -namespace CShocker.Devices; +namespace CShocker.Devices.APIs; -public class OpenShockSerial : OpenShockDevice +public class OpenShockSerial : OpenShockApi { private const int BaudRate = 115200; public SerialPortInfo SerialPortI; @@ -18,10 +18,18 @@ public class OpenShockSerial : OpenShockDevice { this.SerialPortI = serialPortI; this._serialPort = new SerialPort(serialPortI.PortName, BaudRate); - this._serialPort.Open(); + try + { + this._serialPort.Open(); + } + catch (Exception e) + { + this.Logger?.Log(LogLevel.Error, e.Message); + throw; + } } - protected override void ControlInternal(ControlAction action, IShocker shocker, int intensity, int duration) + protected override void ControlInternal(ControlAction action, Shocker shocker, int intensity, int duration) { if (shocker is not OpenShockShocker openShockShocker) { diff --git a/CShocker/Devices/PiShockHttp.cs b/CShocker/Devices/APIs/PiShockHttp.cs similarity index 95% rename from CShocker/Devices/PiShockHttp.cs rename to CShocker/Devices/APIs/PiShockHttp.cs index cc7da22..f32401f 100644 --- a/CShocker/Devices/PiShockHttp.cs +++ b/CShocker/Devices/APIs/PiShockHttp.cs @@ -7,9 +7,9 @@ using CShocker.Shockers; using CShocker.Shockers.Abstract; using Microsoft.Extensions.Logging; -namespace CShocker.Devices; +namespace CShocker.Devices.APIs; -public class PiShockHttp : PiShockDevice +public class PiShockHttp : PiShockApi { // ReSharper disable twice MemberCanBePrivate.Global external usage public string Username, Endpoint, ApiKey; @@ -22,7 +22,7 @@ public class PiShockHttp : PiShockDevice this.ApiKey = apiKey; } - protected override void ControlInternal(ControlAction action, IShocker shocker, int intensity, int duration) + protected override void ControlInternal(ControlAction action, Shocker shocker, int intensity, int duration) { if (shocker is not PiShockShocker piShockShocker) { diff --git a/CShocker/Devices/PiShockSerial.cs b/CShocker/Devices/APIs/PiShockSerial.cs similarity index 92% rename from CShocker/Devices/PiShockSerial.cs rename to CShocker/Devices/APIs/PiShockSerial.cs index f32a538..c2423d8 100644 --- a/CShocker/Devices/PiShockSerial.cs +++ b/CShocker/Devices/APIs/PiShockSerial.cs @@ -5,9 +5,9 @@ using CShocker.Ranges; using CShocker.Shockers.Abstract; using Microsoft.Extensions.Logging; -namespace CShocker.Devices; +namespace CShocker.Devices.APIs; -public class PiShockSerial : PiShockDevice +public class PiShockSerial : PiShockApi { private const int BaudRate = 115200; public SerialPortInfo SerialPortI; @@ -20,7 +20,7 @@ public class PiShockSerial : PiShockDevice throw new NotImplementedException(); } - protected override void ControlInternal(ControlAction action, IShocker shocker, int intensity, int duration) + protected override void ControlInternal(ControlAction action, Shocker shocker, int intensity, int duration) { string json = "{" + "\"cmd\": \"operate\"," + diff --git a/CShocker/Devices/Abstract/Device.cs b/CShocker/Devices/Abstract/Api.cs similarity index 82% rename from CShocker/Devices/Abstract/Device.cs rename to CShocker/Devices/Abstract/Api.cs index 4e57b84..b7d58ea 100644 --- a/CShocker/Devices/Abstract/Device.cs +++ b/CShocker/Devices/Abstract/Api.cs @@ -5,20 +5,20 @@ using Microsoft.Extensions.Logging; namespace CShocker.Devices.Abstract; -public abstract class Device : IDisposable +public abstract class Api : IDisposable { // ReSharper disable 4 times MemberCanBePrivate.Global external use public readonly IntensityRange IntensityRange; public readonly DurationRange DurationRange; protected ILogger? Logger; public readonly DeviceApi ApiType; - private readonly Queue> _queue = new(); + private readonly Queue> _queue = new(); private bool _workQueue = true; // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable private readonly Thread _workQueueThread; private const short CommandDelay = 50; - public void Control(ControlAction action, int? intensity = null, int? duration = null, params IShocker[] shockers) + internal void Control(ControlAction action, int? intensity = null, int? duration = null, params Shocker[] shockers) { int i = intensity ?? IntensityRange.GetRandomRangeValue(); int d = duration ?? DurationRange.GetRandomRangeValue(); @@ -27,16 +27,16 @@ public abstract class Device : IDisposable this.Logger?.Log(LogLevel.Information, "Doing nothing"); return; } - foreach (IShocker shocker in shockers) + foreach (Shocker shocker in shockers) { this.Logger?.Log(LogLevel.Debug, $"Enqueueing {action} {(intensity is not null ? $"Overwrite {i}" : $"{i}")} {(duration is not null ? $"Overwrite {d}" : $"{d}")}"); _queue.Enqueue(new(action, shocker, i ,d)); } } - protected abstract void ControlInternal(ControlAction action, IShocker shocker, int intensity, int duration); + protected abstract void ControlInternal(ControlAction action, Shocker shocker, int intensity, int duration); - protected Device(IntensityRange intensityRange, DurationRange durationRange, DeviceApi apiType, ILogger? logger = null) + protected Api(IntensityRange intensityRange, DurationRange durationRange, DeviceApi apiType, ILogger? logger = null) { this.IntensityRange = intensityRange; this.DurationRange = durationRange; @@ -71,10 +71,10 @@ public abstract class Device : IDisposable public override bool Equals(object? obj) { - return obj is Device d && Equals(d); + return obj is Api d && Equals(d); } - protected bool Equals(Device other) + protected bool Equals(Api other) { return IntensityRange.Equals(other.IntensityRange) && DurationRange.Equals(other.DurationRange) && ApiType == other.ApiType; } diff --git a/CShocker/Devices/Abstract/OpenShockDevice.cs b/CShocker/Devices/Abstract/OpenShockApi.cs similarity index 54% rename from CShocker/Devices/Abstract/OpenShockDevice.cs rename to CShocker/Devices/Abstract/OpenShockApi.cs index 5bf82ac..19fa01f 100644 --- a/CShocker/Devices/Abstract/OpenShockDevice.cs +++ b/CShocker/Devices/Abstract/OpenShockApi.cs @@ -7,13 +7,14 @@ using Newtonsoft.Json.Linq; namespace CShocker.Devices.Abstract; -public abstract class OpenShockDevice : Device +public abstract class OpenShockApi : Api { protected readonly HttpClient HttpClient = new(); public string Endpoint { get; init; } public string ApiKey { get; init; } + private const string DefaultEndpoint = "https://api.shocklink.net"; - public OpenShockDevice(IntensityRange intensityRange, DurationRange durationRange, DeviceApi apiType, string apiKey, string endpoint = "https://api.shocklink.net", ILogger? logger = null) : base(intensityRange, durationRange, apiType, logger) + public OpenShockApi(IntensityRange intensityRange, DurationRange durationRange, DeviceApi apiType, string apiKey, string endpoint = DefaultEndpoint, ILogger? logger = null) : base(intensityRange, durationRange, apiType, logger) { this.Endpoint = endpoint; this.ApiKey = apiKey; @@ -21,10 +22,10 @@ public abstract class OpenShockDevice : Device public override bool Equals(object? obj) { - return obj is OpenShockDevice osd && Equals(osd); + return obj is OpenShockApi osd && Equals(osd); } - private bool Equals(OpenShockDevice other) + private bool Equals(OpenShockApi other) { return base.Equals(other) && Endpoint == other.Endpoint && ApiKey == other.ApiKey; } @@ -34,12 +35,18 @@ public abstract class OpenShockDevice : Device return HashCode.Combine(Endpoint, ApiKey); } - public List GetShockers() + public List GetShockers(string apiKey, string apiEndpoint = DefaultEndpoint, + ILogger? logger = null) + { + return GetShockers(apiKey, this, apiEndpoint, logger); + } + + public static List GetShockers(string apiKey, OpenShockApi api, string apiEndpoint = DefaultEndpoint, ILogger? logger = null) { List shockers = new(); HttpClient httpClient = new(); - HttpRequestMessage requestOwnShockers = new (HttpMethod.Get, $"{Endpoint}/1/shockers/own") + HttpRequestMessage requestOwnShockers = new (HttpMethod.Get, $"{apiEndpoint}/1/shockers/own") { Headers = { @@ -47,21 +54,24 @@ public abstract class OpenShockDevice : Device Accept = { new MediaTypeWithQualityHeaderValue("application/json") } } }; - requestOwnShockers.Headers.Add("OpenShockToken", ApiKey); - this.Logger?.Log(LogLevel.Debug, $"Requesting {requestOwnShockers.RequestUri}"); + requestOwnShockers.Headers.Add("OpenShockToken", apiKey); + logger?.Log(LogLevel.Debug, $"Requesting {requestOwnShockers.RequestUri}"); HttpResponseMessage ownResponse = httpClient.Send(requestOwnShockers); - this.Logger?.Log(!ownResponse.IsSuccessStatusCode ? LogLevel.Error : LogLevel.Debug, + logger?.Log(!ownResponse.IsSuccessStatusCode ? LogLevel.Error : LogLevel.Debug, $"{requestOwnShockers.RequestUri} response: {ownResponse.StatusCode}"); if (!ownResponse.IsSuccessStatusCode) return shockers; StreamReader ownShockerStreamReader = new(ownResponse.Content.ReadAsStream()); string ownShockerJson = ownShockerStreamReader.ReadToEnd(); - this.Logger?.Log(LogLevel.Debug,ownShockerJson); + logger?.Log(LogLevel.Debug,ownShockerJson); JObject ownShockerListJObj = JObject.Parse(ownShockerJson); - shockers.AddRange(ownShockerListJObj.SelectTokens("$.data..shockers[*]").Select(t => t.ToObject())); + shockers.AddRange(ownShockerListJObj.SelectTokens("$.data..shockers[*]").Select(t => + { + return new OpenShockShocker(api, t["name"]!.Value()!, t["id"]!.Value()!, t["rfId"]!.Value(), Enum.Parse(t["model"]!.Value()!), t["createdOn"]!.ToObject(), t["isPaused"]!.Value()); + })); - HttpRequestMessage requestSharedShockers = new (HttpMethod.Get, $"{Endpoint}/1/shockers/shared") + HttpRequestMessage requestSharedShockers = new (HttpMethod.Get, $"{apiEndpoint}/1/shockers/shared") { Headers = { @@ -69,19 +79,22 @@ public abstract class OpenShockDevice : Device Accept = { new MediaTypeWithQualityHeaderValue("application/json") } } }; - requestSharedShockers.Headers.Add("OpenShockToken", ApiKey); - this.Logger?.Log(LogLevel.Debug, $"Requesting {requestSharedShockers.RequestUri}"); + requestSharedShockers.Headers.Add("OpenShockToken", apiKey); + logger?.Log(LogLevel.Debug, $"Requesting {requestSharedShockers.RequestUri}"); HttpResponseMessage sharedResponse = httpClient.Send(requestSharedShockers); - this.Logger?.Log(!sharedResponse.IsSuccessStatusCode ? LogLevel.Error : LogLevel.Debug, + logger?.Log(!sharedResponse.IsSuccessStatusCode ? LogLevel.Error : LogLevel.Debug, $"{requestSharedShockers.RequestUri} response: {sharedResponse.StatusCode}"); if (!sharedResponse.IsSuccessStatusCode) return shockers; StreamReader sharedShockerStreamReader = new(sharedResponse.Content.ReadAsStream()); string sharedShockerJson = sharedShockerStreamReader.ReadToEnd(); - this.Logger?.Log(LogLevel.Debug, sharedShockerJson); + logger?.Log(LogLevel.Debug, sharedShockerJson); JObject sharedShockerListJObj = JObject.Parse(sharedShockerJson); - shockers.AddRange(sharedShockerListJObj.SelectTokens("$.data..shockers[*]").Select(t => t.ToObject())); + shockers.AddRange(sharedShockerListJObj.SelectTokens("$.data..shockers[*]").Select(t => + { + return new OpenShockShocker(api, t["name"]!.Value()!, t["id"]!.Value()!, t["rfId"]!.Value(),Enum.Parse(t["model"]!.Value()!), t["createdOn"]!.ToObject(), t["isPaused"]!.Value()); + })); return shockers; } } \ No newline at end of file diff --git a/CShocker/Devices/Abstract/PiShockApi.cs b/CShocker/Devices/Abstract/PiShockApi.cs new file mode 100644 index 0000000..51a8956 --- /dev/null +++ b/CShocker/Devices/Abstract/PiShockApi.cs @@ -0,0 +1,12 @@ +using CShocker.Devices.Additional; +using CShocker.Ranges; +using Microsoft.Extensions.Logging; + +namespace CShocker.Devices.Abstract; + +public abstract class PiShockApi : Api +{ + protected PiShockApi(IntensityRange intensityRange, DurationRange durationRange, DeviceApi apiType, ILogger? logger = null) : base(intensityRange, durationRange, apiType, logger) + { + } +} \ No newline at end of file diff --git a/CShocker/Devices/Abstract/PiShockDevice.cs b/CShocker/Devices/Abstract/PiShockDevice.cs deleted file mode 100644 index 79747d2..0000000 --- a/CShocker/Devices/Abstract/PiShockDevice.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CShocker.Devices.Additional; -using CShocker.Ranges; -using Microsoft.Extensions.Logging; - -namespace CShocker.Devices.Abstract; - -public abstract class PiShockDevice : Device -{ - protected PiShockDevice(IntensityRange intensityRange, DurationRange durationRange, DeviceApi apiType, ILogger? logger = null) : base(intensityRange, durationRange, apiType, logger) - { - } -} \ No newline at end of file diff --git a/CShocker/Devices/Additional/DeviceJsonConverter.cs b/CShocker/Devices/Additional/ApiJsonConverter.cs similarity index 95% rename from CShocker/Devices/Additional/DeviceJsonConverter.cs rename to CShocker/Devices/Additional/ApiJsonConverter.cs index 722eb6b..2d754c2 100644 --- a/CShocker/Devices/Additional/DeviceJsonConverter.cs +++ b/CShocker/Devices/Additional/ApiJsonConverter.cs @@ -1,15 +1,16 @@ using CShocker.Devices.Abstract; +using CShocker.Devices.APIs; using CShocker.Ranges; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace CShocker.Devices.Additional; -public class DeviceJsonConverter : JsonConverter +public class ApiJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { - return (objectType == typeof(Device)); + return (objectType == typeof(Api)); } public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) diff --git a/CShocker/Shockers/Abstract/Shocker.cs b/CShocker/Shockers/Abstract/Shocker.cs index caab141..e53fe67 100644 --- a/CShocker/Shockers/Abstract/Shocker.cs +++ b/CShocker/Shockers/Abstract/Shocker.cs @@ -1,5 +1,24 @@ -namespace CShocker.Shockers.Abstract; +using CShocker.Devices.Abstract; +using CShocker.Devices.Additional; -public interface IShocker +namespace CShocker.Shockers.Abstract; + +public abstract class Shocker : IDisposable { + public Api Api { get; } + + internal Shocker(Api api) + { + this.Api = api; + } + + public void Control(ControlAction action, int? intensity = null, int? duration = null) + { + this.Api.Control(action, intensity, duration, this); + } + + public void Dispose() + { + Api.Dispose(); + } } \ No newline at end of file diff --git a/CShocker/Shockers/Additional/ShockerJsonConverter.cs b/CShocker/Shockers/Additional/ShockerJsonConverter.cs index 168279a..7ac7407 100644 --- a/CShocker/Shockers/Additional/ShockerJsonConverter.cs +++ b/CShocker/Shockers/Additional/ShockerJsonConverter.cs @@ -1,4 +1,5 @@ -using CShocker.Shockers.Abstract; +using CShocker.Devices.Abstract; +using CShocker.Shockers.Abstract; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -8,7 +9,7 @@ public class ShockerJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { - return (objectType == typeof(IShocker)); + return (objectType == typeof(Shocker)); } public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) @@ -16,22 +17,22 @@ public class ShockerJsonConverter : JsonConverter JObject jo = JObject.Load(reader); if (jo.ContainsKey("model")) //OpenShockShocker { - return new OpenShockShocker() - { - name = jo.SelectToken("name")!.Value()!, - id = jo.SelectToken("id")!.Value()!, - rfId = jo.SelectToken("rfId")!.Value(), - model = (OpenShockShocker.OpenShockModel)jo.SelectToken("model")!.Value(), - createdOn = jo.SelectToken("createdOn")!.Value(), - isPaused = jo.SelectToken("isPaused")!.Value() - }; + return new OpenShockShocker( + jo.SelectToken("api")!.ToObject()!, + jo.SelectToken("name")!.Value()!, + jo.SelectToken("id")!.Value()!, + jo.SelectToken("rfId")!.Value(), + (OpenShockShocker.OpenShockModel)jo.SelectToken("model")!.Value(), + jo.SelectToken("createdOn")!.Value(), + jo.SelectToken("isPaused")!.Value() + ); } else //PiShockShocker { - return new PiShockShocker() - { - Code = jo.SelectToken("Code")!.Value()! - }; + return new PiShockShocker( + jo.SelectToken("api")!.ToObject()!, + jo.SelectToken("Code")!.Value()! + ); } throw new Exception(); } diff --git a/CShocker/Shockers/OpenShockShocker.cs b/CShocker/Shockers/OpenShockShocker.cs index 0681332..477042f 100644 --- a/CShocker/Shockers/OpenShockShocker.cs +++ b/CShocker/Shockers/OpenShockShocker.cs @@ -1,11 +1,12 @@ using System.Diagnostics.CodeAnalysis; +using CShocker.Devices.Abstract; using CShocker.Shockers.Abstract; namespace CShocker.Shockers; #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. [SuppressMessage("ReSharper", "InconsistentNaming")] -public struct OpenShockShocker : IShocker +public class OpenShockShocker : Shocker { public string name, id; public short rfId; @@ -13,6 +14,18 @@ public struct OpenShockShocker : IShocker public DateTime createdOn; public bool isPaused; + public OpenShockShocker(Api api, string name, string id, short rfId, OpenShockModel model, DateTime createdOn, bool isPaused) : base (api) + { + if (api is not OpenShockApi) + throw new Exception($"API-Type {api.GetType().FullName} is not usable with Shocker {this.GetType().FullName}"); + this.name = name; + this.id = id; + this.rfId = rfId; + this.model = model; + this.createdOn = createdOn; + this.isPaused = isPaused; + } + public enum OpenShockModel : byte { CaiXianlin = 0, diff --git a/CShocker/Shockers/PiShockShocker.cs b/CShocker/Shockers/PiShockShocker.cs index 670f120..bdc660d 100644 --- a/CShocker/Shockers/PiShockShocker.cs +++ b/CShocker/Shockers/PiShockShocker.cs @@ -1,8 +1,9 @@ -using CShocker.Shockers.Abstract; +using CShocker.Devices.Abstract; +using CShocker.Shockers.Abstract; namespace CShocker.Shockers; -public struct PiShockShocker : IShocker +public class PiShockShocker : Shocker { public string Code; @@ -20,4 +21,11 @@ public struct PiShockShocker : IShocker { return Code.GetHashCode(); } + + public PiShockShocker(Api api, string code) : base(api) + { + if (api is not PiShockApi) + throw new Exception($"API-Type {api.GetType().FullName} is not usable with Shocker {this.GetType().FullName}"); + Code = code; + } } \ No newline at end of file diff --git a/TestApp/Logger.cs b/TestApp/Logger.cs deleted file mode 100644 index 9567a31..0000000 --- a/TestApp/Logger.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Microsoft.Extensions.Logging; - -namespace TestApp; - -public class Logger : ILogger -{ - private LogLevel _enabledLoglevel; - private readonly ConsoleColor _defaultForegroundColor = Console.ForegroundColor; - private readonly ConsoleColor _defaultBackgroundColor = Console.BackgroundColor; - - public Logger(LogLevel logLevel = LogLevel.Trace) - { - _enabledLoglevel = logLevel; - } - - public void UpdateLogLevel(LogLevel logLevel) - { - this._enabledLoglevel = logLevel; - } - - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) - { - if (!IsEnabled(logLevel)) - return; - Console.ForegroundColor = ForegroundColorForLogLevel(logLevel); - Console.BackgroundColor = BackgroundColorForLogLevel(logLevel); - Console.Write(logLevel.ToString()[..3].ToUpper()); - Console.ResetColor(); - // ReSharper disable once LocalizableElement - Console.Write($" [{DateTime.UtcNow:HH:mm:ss.fff}] "); - Console.WriteLine(formatter.Invoke(state, exception)); - } - - public bool IsEnabled(LogLevel logLevel) - { - return logLevel >= _enabledLoglevel; - } - - public IDisposable? BeginScope(TState state) where TState : notnull - { - return null; - } - - private ConsoleColor ForegroundColorForLogLevel(LogLevel logLevel) - { - return logLevel switch - { - LogLevel.Error or LogLevel.Critical => ConsoleColor.Black, - LogLevel.Debug => ConsoleColor.Black, - LogLevel.Information => ConsoleColor.White, - _ => _defaultForegroundColor - }; - } - - private ConsoleColor BackgroundColorForLogLevel(LogLevel logLevel) - { - return logLevel switch - { - LogLevel.Error or LogLevel.Critical => ConsoleColor.Red, - LogLevel.Debug => ConsoleColor.Yellow, - LogLevel.Information => ConsoleColor.Black, - _ => _defaultBackgroundColor - }; - } -} \ No newline at end of file diff --git a/TestApp/Program.cs b/TestApp/Program.cs index 0babb27..be7458c 100644 --- a/TestApp/Program.cs +++ b/TestApp/Program.cs @@ -1,35 +1,33 @@ -using CShocker.Devices; -using CShocker.Devices.Abstract; +using CShocker.Devices.Abstract; using CShocker.Devices.Additional; +using CShocker.Devices.APIs; using CShocker.Ranges; using CShocker.Shockers; -using CShocker.Shockers.Abstract; -using CShocker.Shockers.Additional; +using GlaxLogger; +using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using TestApp; -Logger logger = new (); -List shockers = new(); +Logger logger = new (LogLevel.Trace); Console.WriteLine("OpenShock API Key:"); string? apiKey = Console.ReadLine(); while(apiKey is null || apiKey.Length < 1) apiKey = Console.ReadLine(); - -OpenShockHttp openShockHttp = new (new IntensityRange(30, 50), new DurationRange(1000, 1000), apiKey, logger: logger); -shockers = openShockHttp.GetShockers(); -openShockHttp.Control(ControlAction.Vibrate, 20, 1000, shockers.First()); - -File.WriteAllText("devices.json", JsonConvert.SerializeObject(openShockHttp)); -OpenShockHttp deserialized = JsonConvert.DeserializeObject(File.ReadAllText("devices.json"))!; -Thread.Sleep(1100); //Wait for previous to end -deserialized.Control(ControlAction.Vibrate, 20, 1000, shockers.First()); -openShockHttp.Dispose(); -deserialized.Dispose(); - - /* +OpenShockHttp openShockHttp = new (new IntensityRange(30, 50), new DurationRange(1000, 1000), apiKey, logger: logger); +OpenShockShocker shocker = openShockHttp.GetShockers(apiKey).First(); +shocker.Control(ControlAction.Vibrate, 20, 1000); + +File.WriteAllText("shockers.json", JsonConvert.SerializeObject(shocker)); +OpenShockShocker deserialized = JsonConvert.DeserializeObject(File.ReadAllText("shockers.json"), new ApiJsonConverter())!; +Thread.Sleep(1100); //Wait for previous to end +deserialized.Control(ControlAction.Vibrate, 20, 1000); +shocker.Dispose(); +deserialized.Dispose(); +*/ + + #pragma warning disable CA1416 List serialPorts = SerialHelper.GetSerialPorts(); @@ -49,15 +47,11 @@ while (!int.TryParse(selectedPortStr, out selectedPort) || selectedPort < 0 || s } OpenShockSerial openShockSerial = new(new IntensityRange(30, 50), new DurationRange(1000, 1000),serialPorts[selectedPort], apiKey, logger: logger); -shockers = openShockSerial.GetShockers(); -openShockSerial.Control(ControlAction.Vibrate, 20, 1000, shockers.First()); -File.WriteAllText("devices.json", JsonConvert.SerializeObject(openShockSerial)); -OpenShockHttp deserialized = JsonConvert.DeserializeObject(File.ReadAllText("devices.json"))!; -openShockSerial.Dispose(); +OpenShockShocker shocker = openShockSerial.GetShockers(apiKey).First(); +shocker.Control(ControlAction.Vibrate, 20, 1000); +File.WriteAllText("shockers.json", JsonConvert.SerializeObject(shocker)); +OpenShockShocker deserialized = JsonConvert.DeserializeObject(File.ReadAllText("shockers.json"), new ApiJsonConverter())!; +shocker.Dispose(); deserialized.Dispose(); -*/ -foreach(OpenShockShocker s in shockers) - Console.Write(s); -File.WriteAllText("shockers.json", JsonConvert.SerializeObject(shockers)); -List deserializedShockers = JsonConvert.DeserializeObject>(File.ReadAllText("shockers.json"), new ShockerJsonConverter())!; \ No newline at end of file +logger.Dispose(); \ No newline at end of file diff --git a/TestApp/TestApp.csproj b/TestApp/TestApp.csproj index 2f79b9c..de62ce7 100644 --- a/TestApp/TestApp.csproj +++ b/TestApp/TestApp.csproj @@ -11,4 +11,10 @@ + + + ..\..\GlaxLogger\GlaxLogger\bin\Debug\net7.0\GlaxLogger.dll + + +