Compare commits

..

11 Commits

Author SHA1 Message Date
60746d66df Version 2024-02-12 03:07:18 +01:00
eebf15804a ToString fancy 2024-02-12 03:06:28 +01:00
2c7da0352b Fancier output 2024-02-12 02:05:22 +01:00
17206bfb8c Let Constructor throw Exception instead of method 2024-02-12 02:05:13 +01:00
4839c12340 Add RandomValueWithinLimits to IntegerRange 2024-02-12 02:04:58 +01:00
1eed03ac14 GetHashcode and Equals usage 2024-02-12 02:04:45 +01:00
f6e8ddb91d ToString more conventional 2024-02-12 02:04:09 +01:00
8d70879c68 Capitalized FieldNames onn public fields 2024-02-12 02:03:35 +01:00
639b813fb6 Dependency from Nuget 2024-02-12 02:02:45 +01:00
171b057d58 Renamed to IsValueWithinLimits 2024-02-12 02:02:30 +01:00
bb8959160a Mark exposed fields and methods 2024-02-12 02:02:10 +01:00
16 changed files with 90 additions and 62 deletions

View File

@ -7,7 +7,7 @@
<Authors>Glax</Authors> <Authors>Glax</Authors>
<RepositoryUrl>https://github.com/C9Glax/CShocker</RepositoryUrl> <RepositoryUrl>https://github.com/C9Glax/CShocker</RepositoryUrl>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>
<Version>2.3.1</Version> <Version>2.4.0</Version>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>

View File

@ -19,7 +19,7 @@ public class OpenShockHttp : OpenShockApi
string json = "{" + string json = "{" +
" \"shocks\": [" + " \"shocks\": [" +
" {" + " {" +
$" \"id\": \"{openShockShocker.id}\"," + $" \"id\": \"{openShockShocker.ID}\"," +
$" \"type\": {ControlActionToByte(action)}," + $" \"type\": {ControlActionToByte(action)}," +
$" \"intensity\": {intensity}," + $" \"intensity\": {intensity}," +
$" \"duration\": {duration}" + $" \"duration\": {duration}" +

View File

@ -36,8 +36,8 @@ public class OpenShockSerial : OpenShockApi
return; return;
} }
string json = "rftransmit {" + string json = "rftransmit {" +
$"\"model\":\"{Enum.GetName(openShockShocker.model)!.ToLower()}\"," + $"\"model\":\"{Enum.GetName(openShockShocker.Model)!.ToLower()}\"," +
$"\"id\":{openShockShocker.rfId}," + $"\"id\":{openShockShocker.RfId}," +
$"\"type\":\"{ControlActionToString(action)}\"," + $"\"type\":\"{ControlActionToString(action)}\"," +
$"\"intensity\":{intensity}," + $"\"intensity\":{intensity}," +
$"\"durationMs\":{duration}" + $"\"durationMs\":{duration}" +

View File

@ -8,8 +8,8 @@ namespace CShocker.Devices.APIs;
public class PiShockHttp : PiShockApi public class PiShockHttp : PiShockApi
{ {
// ReSharper disable twice MemberCanBePrivate.Global external usage // ReSharper disable thrice MemberCanBePrivate.Global -> Exposed
public string Username, Endpoint, ApiKey; public readonly string Username, Endpoint, ApiKey;
public PiShockHttp(string apiKey, string username, string endpoint = "https://do.pishock.com/api/apioperate", ILogger? logger = null) : base(DeviceApi.PiShockHttp, logger) public PiShockHttp(string apiKey, string username, string endpoint = "https://do.pishock.com/api/apioperate", ILogger? logger = null) : base(DeviceApi.PiShockHttp, logger)
{ {

View File

@ -1,7 +1,6 @@
using System.IO.Ports; using System.IO.Ports;
using CShocker.Devices.Abstract; using CShocker.Devices.Abstract;
using CShocker.Devices.Additional; using CShocker.Devices.Additional;
using CShocker.Ranges;
using CShocker.Shockers.Abstract; using CShocker.Shockers.Abstract;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -10,7 +9,8 @@ namespace CShocker.Devices.APIs;
public class PiShockSerial : PiShockApi public class PiShockSerial : PiShockApi
{ {
private const int BaudRate = 115200; private const int BaudRate = 115200;
public SerialPortInfo SerialPortI; // ReSharper disable once MemberCanBePrivate.Global -> Exposed
public readonly SerialPortInfo SerialPortI;
private readonly SerialPort _serialPort; private readonly SerialPort _serialPort;
public PiShockSerial(DeviceApi apiType, SerialPortInfo serialPortI, ILogger? logger = null) : base(apiType, logger) public PiShockSerial(DeviceApi apiType, SerialPortInfo serialPortI, ILogger? logger = null) : base(apiType, logger)

View File

@ -7,7 +7,7 @@ namespace CShocker.Devices.Abstract;
public abstract class Api : IDisposable public abstract class Api : IDisposable
{ {
// ReSharper disable 4 times MemberCanBePrivate.Global external use // ReSharper disable 4 times MemberCanBePrivate.Global -> Exposed
protected ILogger? Logger; protected ILogger? Logger;
public readonly DeviceApi ApiType; public readonly DeviceApi ApiType;
private readonly Queue<ValueTuple<ControlAction, Shocker, int, int>> _queue = new(); private readonly Queue<ValueTuple<ControlAction, Shocker, int, int>> _queue = new();
@ -25,12 +25,12 @@ public abstract class Api : IDisposable
this.Logger?.Log(LogLevel.Information, "No action defined."); this.Logger?.Log(LogLevel.Information, "No action defined.");
enqueueItem = false; enqueueItem = false;
} }
if (!ValidIntensityRange.ValueWithinLimits(intensity)) if (!ValidIntensityRange.IsValueWithinLimits(intensity))
{ {
this.Logger?.Log(LogLevel.Information, $"Value not within allowed {nameof(intensity)}-Range ({ValidIntensityRange.RangeString()}): {intensity}"); this.Logger?.Log(LogLevel.Information, $"Value not within allowed {nameof(intensity)}-Range ({ValidIntensityRange.RangeString()}): {intensity}");
enqueueItem = false; enqueueItem = false;
} }
if (!ValidDurationRange.ValueWithinLimits(duration)) if (!ValidDurationRange.IsValueWithinLimits(duration))
{ {
this.Logger?.Log(LogLevel.Information, $"Value not within allowed {nameof(duration)}-Range ({ValidIntensityRange.RangeString()}): {duration}"); this.Logger?.Log(LogLevel.Information, $"Value not within allowed {nameof(duration)}-Range ({ValidIntensityRange.RangeString()}): {duration}");
enqueueItem = false; enqueueItem = false;
@ -42,7 +42,7 @@ public abstract class Api : IDisposable
} }
foreach (Shocker shocker in shockers) foreach (Shocker shocker in shockers)
{ {
this.Logger?.Log(LogLevel.Debug, $"Enqueueing {action} {intensity} {duration}"); this.Logger?.Log(LogLevel.Debug, $"Enqueueing {action} Intensity: {intensity} Duration: {duration}\nShocker:\n{shocker}");
_queue.Enqueue(new(action, shocker, intensity, duration)); _queue.Enqueue(new(action, shocker, intensity, duration));
} }
} }
@ -64,7 +64,7 @@ public abstract class Api : IDisposable
while (_workOnQueue) while (_workOnQueue)
if (_queue.Count > 0 && _queue.Dequeue() is { } action) if (_queue.Count > 0 && _queue.Dequeue() is { } action)
{ {
this.Logger?.Log(LogLevel.Information, $"{action.Item1} {action.Item2} {action.Item3} {action.Item4}"); this.Logger?.Log(LogLevel.Information, $"Executing: {Enum.GetName(action.Item1)} Intensity: {action.Item3} Duration: {action.Item4}\nShocker:\n{action.Item2.ToString()}");
ControlInternal(action.Item1, action.Item2, action.Item3, action.Item4); ControlInternal(action.Item1, action.Item2, action.Item3, action.Item4);
Thread.Sleep(action.Item4 + CommandDelay); Thread.Sleep(action.Item4 + CommandDelay);
} }
@ -92,7 +92,7 @@ public abstract class Api : IDisposable
public override int GetHashCode() public override int GetHashCode()
{ {
return HashCode.Combine(ApiType); return ApiType.GetHashCode();
} }
public void Dispose() public void Dispose()

View File

@ -8,10 +8,12 @@ namespace CShocker.Devices.Abstract;
public abstract class OpenShockApi : Api public abstract class OpenShockApi : Api
{ {
// ReSharper disable twice MemberCanBeProtected.Global -> Exposed
public string Endpoint { get; init; } public string Endpoint { get; init; }
public string ApiKey { get; init; } public string ApiKey { get; init; }
private const string DefaultEndpoint = "https://api.shocklink.net"; private const string DefaultEndpoint = "https://api.shocklink.net";
// ReSharper disable once PublicConstructorInAbstractClass -> Exposed
public OpenShockApi(DeviceApi apiType, string apiKey, string endpoint = DefaultEndpoint, ILogger? logger = null) : base(apiType, new IntegerRange(0, 100), new IntegerRange(300, 30000), logger) public OpenShockApi(DeviceApi apiType, string apiKey, string endpoint = DefaultEndpoint, ILogger? logger = null) : base(apiType, new IntegerRange(0, 100), new IntegerRange(300, 30000), logger)
{ {
this.Endpoint = endpoint; this.Endpoint = endpoint;
@ -25,7 +27,7 @@ public abstract class OpenShockApi : Api
private bool Equals(OpenShockApi other) private bool Equals(OpenShockApi other)
{ {
return base.Equals(other) && Endpoint == other.Endpoint && ApiKey == other.ApiKey; return base.Equals(other) && Endpoint.Equals(other.Endpoint) && ApiKey.Equals(other.ApiKey);
} }
public override int GetHashCode() public override int GetHashCode()
@ -33,12 +35,13 @@ public abstract class OpenShockApi : Api
return HashCode.Combine(Endpoint, ApiKey); return HashCode.Combine(Endpoint, ApiKey);
} }
public List<OpenShockShocker> GetShockers() public IEnumerable<OpenShockShocker> GetShockers()
{ {
return GetShockers(this.ApiKey, this, this.Endpoint, this.Logger); return GetShockers(this.ApiKey, this, this.Endpoint, this.Logger);
} }
public static List<OpenShockShocker> GetShockers(string apiKey, OpenShockApi api, string apiEndpoint = DefaultEndpoint, ILogger? logger = null) // ReSharper disable once MemberCanBePrivate.Global
public static IEnumerable<OpenShockShocker> GetShockers(string apiKey, OpenShockApi api, string apiEndpoint = DefaultEndpoint, ILogger? logger = null)
{ {
List<OpenShockShocker> shockers = new(); List<OpenShockShocker> shockers = new();

View File

@ -1,7 +1,8 @@
namespace CShocker.Devices.Abstract; namespace CShocker.Devices.Abstract;
public struct SerialPortInfo public readonly struct SerialPortInfo
{ {
// ReSharper disable thrice MemberCanBePrivate.Global -> Exposed
public readonly string? PortName, Description, Manufacturer, DeviceID; public readonly string? PortName, Description, Manufacturer, DeviceID;
public SerialPortInfo(string? portName, string? description, string? manufacturer, string? deviceID) public SerialPortInfo(string? portName, string? description, string? manufacturer, string? deviceID)
@ -14,7 +15,12 @@ public struct SerialPortInfo
public override string ToString() public override string ToString()
{ {
return return $"{string.Join("\n\t",
$"{GetType().Name}\nPortName: {PortName}\nDescription: {Description}\nManufacturer: {Manufacturer}\nDeviceID: {DeviceID}\n\r"; $"{GetType().Name}",
$"PortName: {PortName}",
$"Description: {Description}",
$"Manufacturer: {Manufacturer}",
$"DeviceID: {DeviceID}")}" +
$"\n\r";
} }
} }

View File

@ -26,14 +26,19 @@ public static class ApiHttpClient
new StringContent(jsonContent, Encoding.UTF8, new MediaTypeHeaderValue("application/json")); new StringContent(jsonContent, Encoding.UTF8, new MediaTypeHeaderValue("application/json"));
foreach ((string, string) customHeader in customHeaders) foreach ((string, string) customHeader in customHeaders)
request.Headers.Add(customHeader.Item1, customHeader.Item2); request.Headers.Add(customHeader.Item1, customHeader.Item2);
logger?.Log(LogLevel.Debug, $"Request-URI: {request.RequestUri}\n\r" + logger?.Log(LogLevel.Debug, string.Join("\n\t",
$"Request-Headers: \n\t{string.Join("\n\t", request.Headers.Select(h => $"{h.Key} {string.Join(", ", h.Value)}"))}\n\r" + "Request:",
$"Request-Content: {request.Content?.ReadAsStringAsync().Result}"); $"\u251c\u2500\u2500 URI: {request.RequestUri}",
$"\u251c\u2500\u2510 Headers: {string.Concat(request.Headers.Select(h => $"\n\t\u2502 {(request.Headers.Last().Key.Equals(h.Key) ? "\u2514" : "\u251c")} {h.Key}: {string.Join(", ", h.Value)}"))}",
$"\u2514\u2500\u2500 Content: {request.Content?.ReadAsStringAsync().Result}"));
HttpClient httpClient = new(); HttpClient httpClient = new();
HttpResponseMessage response = httpClient.Send(request); HttpResponseMessage response = httpClient.Send(request);
logger?.Log(!response.IsSuccessStatusCode ? LogLevel.Error : LogLevel.Debug, logger?.Log(!response.IsSuccessStatusCode ? LogLevel.Error : LogLevel.Debug, string.Join("\n\t",
$"{request.RequestUri} response: {response.StatusCode}"); "Request:",
$"\u251c\u2500\u2500 URI: {request.RequestUri}",
$"\u251c\u2500\u2510 Headers: {string.Concat(response.Headers.Select(h => $"\n\t\u2502 {(response.Headers.Last().Key.Equals(h.Key) ? "\u2514" : "\u251c")} {h.Key}: {string.Join(", ", h.Value)}"))}",
$"\u2514\u2500\u2500 Content: {response.Content?.ReadAsStringAsync().Result}"));
httpClient.Dispose(); httpClient.Dispose();
return response; return response;
} }

View File

@ -26,7 +26,7 @@ public class ApiJsonConverter : JsonConverter
case DeviceApi.PiShockHttp: case DeviceApi.PiShockHttp:
return jo.ToObject<PiShockHttp>()!; return jo.ToObject<PiShockHttp>()!;
case DeviceApi.PiShockSerial: case DeviceApi.PiShockSerial:
throw new NotImplementedException(); return jo.ToObject<PiShockSerial>()!;
default: default:
throw new Exception(); throw new Exception();
} }

View File

@ -2,6 +2,7 @@
public readonly struct IntegerRange public readonly struct IntegerRange
{ {
// ReSharper disable twice MemberCanBePrivate.Global -> Exposed
public readonly int Min, Max; public readonly int Min, Max;
public IntegerRange(int min, int max) public IntegerRange(int min, int max)
@ -10,11 +11,16 @@ public readonly struct IntegerRange
this.Max = max; this.Max = max;
} }
public bool ValueWithinLimits(int value) public bool IsValueWithinLimits(int value)
{ {
return value >= this.Min && value <= this.Max; return value >= this.Min && value <= this.Max;
} }
public int RandomValueWithinLimits()
{
return Random.Shared.Next(this.Min, this.Max);
}
internal string RangeString() internal string RangeString()
{ {
return $"{this.Min}-{this.Max}"; return $"{this.Min}-{this.Max}";

View File

@ -5,6 +5,7 @@ namespace CShocker.Shockers.Abstract;
public abstract class Shocker : IDisposable public abstract class Shocker : IDisposable
{ {
// ReSharper disable once MemberCanBePrivate.Global -> Exposed
public Api Api { get; } public Api Api { get; }
internal Shocker(Api api) internal Shocker(Api api)

View File

@ -22,7 +22,6 @@ public class ShockerJsonConverter : JsonConverter
{ {
return jo.ToObject<PiShockShocker>(serializer)!; return jo.ToObject<PiShockShocker>(serializer)!;
} }
throw new Exception();
} }
public override bool CanWrite => false; public override bool CanWrite => false;
@ -32,6 +31,6 @@ public class ShockerJsonConverter : JsonConverter
/// </summary> /// </summary>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{ {
throw new Exception("Dont call this"); throw new NotImplementedException("Dont call this");
} }
} }

View File

@ -1,29 +1,27 @@
using System.Diagnostics.CodeAnalysis; using CShocker.Devices.Abstract;
using CShocker.Devices.Abstract;
using CShocker.Shockers.Abstract; using CShocker.Shockers.Abstract;
namespace CShocker.Shockers; 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 class OpenShockShocker : Shocker public class OpenShockShocker : Shocker
{ {
public string name, id; // ReSharper disable thrice MemberCanBePrivate.Global -> Exposed
public short rfId; public readonly string Name, ID;
public OpenShockModel model; public readonly short RfId;
public DateTime createdOn; public readonly OpenShockModel Model;
public bool isPaused; public readonly DateTime CreatedOn;
public readonly bool IsPaused;
public OpenShockShocker(Api api, string name, string id, short rfId, OpenShockModel model, DateTime createdOn, bool isPaused) : base (api) public OpenShockShocker(Api api, string name, string id, short rfId, OpenShockModel model, DateTime createdOn, bool isPaused) : base (api)
{ {
if (api is not OpenShockApi) if (api is not OpenShockApi)
throw new Exception($"API-Type {api.GetType().FullName} is not usable with Shocker {this.GetType().FullName}"); throw new Exception($"API-Type {api.GetType().FullName} is not usable with Shocker {this.GetType().FullName}");
this.name = name; this.Name = name;
this.id = id; this.ID = id;
this.rfId = rfId; this.RfId = rfId;
this.model = model; this.Model = model;
this.createdOn = createdOn; this.CreatedOn = createdOn;
this.isPaused = isPaused; this.IsPaused = isPaused;
} }
public enum OpenShockModel : byte public enum OpenShockModel : byte
@ -34,13 +32,16 @@ public class OpenShockShocker : Shocker
public override string ToString() public override string ToString()
{ {
return $"{GetType().Name}\n" + const int tabWidth = -12;
$"Name: {name}\n" + return $"\t{string.Join("\n\t",
$"ID: {id}\n" + $"\u251c {"Type",tabWidth}: {GetType().Name}",
$"RF-ID: {rfId}\n" + $"\u251c {"Name",tabWidth}: {Name}",
$"Model: {Enum.GetName(model)}\n" + $"\u251c {"ID",tabWidth}: {ID}",
$"Created On: {createdOn}\n" + $"\u251c {"RF-ID",tabWidth}: {RfId}",
$"Paused: {isPaused}\n\r"; $"\u251c {"Model",tabWidth}: {Enum.GetName(Model)}",
$"\u251c {"Created On",tabWidth}: {CreatedOn}",
$"\u2514 {"Paused",tabWidth}: {IsPaused}")}" +
$"\n\r";
} }
public override bool Equals(object? obj) public override bool Equals(object? obj)
@ -51,11 +52,11 @@ public class OpenShockShocker : Shocker
private bool Equals(OpenShockShocker other) private bool Equals(OpenShockShocker other)
{ {
return id == other.id && rfId == other.rfId && model == other.model && createdOn.Equals(other.createdOn); return ID == other.ID;
} }
public override int GetHashCode() public override int GetHashCode()
{ {
return HashCode.Combine(id, rfId, (int)model, createdOn); return ID.GetHashCode();
} }
} }

View File

@ -5,7 +5,14 @@ namespace CShocker.Shockers;
public class PiShockShocker : Shocker public class PiShockShocker : Shocker
{ {
public string Code; public readonly string Code;
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;
}
public override bool Equals(object? obj) public override bool Equals(object? obj)
{ {
@ -21,11 +28,13 @@ public class PiShockShocker : Shocker
{ {
return Code.GetHashCode(); return Code.GetHashCode();
} }
public PiShockShocker(Api api, string code) : base(api) public override string ToString()
{ {
if (api is not PiShockApi) const int tabWidth = -5;
throw new Exception($"API-Type {api.GetType().FullName} is not usable with Shocker {this.GetType().FullName}"); return $"{string.Join("\n\t",
Code = code; $"\u251c {"Type",tabWidth}: {GetType().Name}",
$"\u2514 {"Code",tabWidth}: {Code}")}" +
$"\n\r";
} }
} }

View File

@ -12,9 +12,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="GlaxLogger"> <PackageReference Include="GlaxLogger" Version="1.0.6" />
<HintPath>..\..\GlaxLogger\GlaxLogger\bin\Debug\net7.0\GlaxLogger.dll</HintPath>
</Reference>
</ItemGroup> </ItemGroup>
</Project> </Project>