Compare commits
14 Commits
60746d66df
...
master
Author | SHA1 | Date | |
---|---|---|---|
34fb4d89bd | |||
828a1a2bfa | |||
0b98638cd5 | |||
74d30ba1b9 | |||
385dba1cf3 | |||
1ff67a5b8b | |||
c55592cd90 | |||
b497117b62 | |||
73c19a3f8f | |||
318598f62a | |||
cf0a7c630d | |||
ce0a287e4e | |||
7693aa8b09 | |||
746e153cb5 |
12
.idea/.idea.CShocker/.idea/riderPublish.xml
generated
Normal file
12
.idea/.idea.CShocker/.idea/riderPublish.xml
generated
Normal file
@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="LocationsWithSilentDeleteHolder">
|
||||
<option name="locations">
|
||||
<list>
|
||||
<option value="$PROJECT_DIR$/CShocker/bin/Release/net9.0/win-x64" />
|
||||
<option value="$PROJECT_DIR$/CShocker/bin/Release/net9.0/linux-x64/publish" />
|
||||
<option value="$PROJECT_DIR$/CShocker/bin/Release/net9.0/win-x64/publish" />
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
@ -1,5 +1,7 @@
|
||||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=C_003A_005CUsers_005CGlax_005CRiderProjects_005CGlaxLogger_005CGlaxLogger_005Cbin_005CDebug_005Cnet7_002E0_005CGlaxLogger_002Edll/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AHttpClient_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003Fc439425da351c75ac7d966a1cc8324b51a9c471865af79d2f2f3fcb65e392_003FHttpClient_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AThrowHelper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2024_002E3_003Fresharper_002Dhost_003FSourcesCache_003F2c8e7ca976f350cba9836d5565dac56b11e0b56656fa786460eb1395857a6fa_003FThrowHelper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/Environment/AssemblyExplorer/XmlDocument/@EntryValue"><AssemblyExplorer>
|
||||
<Assembly Path="C:\Users\Glax\RiderProjects\GlaxLogger\GlaxLogger\bin\Debug\net7.0\GlaxLogger.dll" />
|
||||
</AssemblyExplorer></s:String></wpf:ResourceDictionary>
|
@ -1,20 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Authors>Glax</Authors>
|
||||
<RepositoryUrl>https://github.com/C9Glax/CShocker</RepositoryUrl>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<Version>2.4.0</Version>
|
||||
<Version>3.1.0</Version>
|
||||
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
|
||||
<LangVersion>latestmajor</LangVersion>
|
||||
<PackageProjectUrl>https://github.com/C9Glax/CShocker</PackageProjectUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="System.IO.Ports" Version="8.0.0" />
|
||||
<PackageReference Include="System.Management" Version="8.0.0" />
|
||||
<PackageReference Include="System.IO.Ports" Version="9.0.1" />
|
||||
<PackageReference Include="System.Management" Version="9.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
@ -20,7 +20,7 @@ public class OpenShockHttp : OpenShockApi
|
||||
" \"shocks\": [" +
|
||||
" {" +
|
||||
$" \"id\": \"{openShockShocker.ID}\"," +
|
||||
$" \"type\": {ControlActionToByte(action)}," +
|
||||
$" \"type\": \"{Enum.GetName(action)}\"," +
|
||||
$" \"intensity\": {intensity}," +
|
||||
$" \"duration\": {duration}" +
|
||||
" }" +
|
||||
@ -31,18 +31,7 @@ public class OpenShockHttp : OpenShockApi
|
||||
ApiHttpClient.MakeAPICall(HttpMethod.Post, $"{Endpoint}/2/shockers/control", json, this.Logger, new ValueTuple<string, string>("OpenShockToken", ApiKey));
|
||||
}
|
||||
|
||||
private byte ControlActionToByte(ControlAction action)
|
||||
{
|
||||
return action switch
|
||||
{
|
||||
ControlAction.Beep => 3,
|
||||
ControlAction.Vibrate => 2,
|
||||
ControlAction.Shock => 1,
|
||||
_ => 0
|
||||
};
|
||||
}
|
||||
|
||||
public OpenShockHttp(string apiKey, string endpoint = "https://api.shocklink.net", ILogger? logger = null) : base(DeviceApi.OpenShockHttp, apiKey, endpoint, logger)
|
||||
public OpenShockHttp(string apiKey, string? endpoint = null, ILogger? logger = null) : base(DeviceApi.OpenShockHttp, apiKey, endpoint??DefaultEndpoint, logger)
|
||||
{
|
||||
}
|
||||
}
|
@ -13,7 +13,7 @@ public class OpenShockSerial : OpenShockApi
|
||||
public SerialPortInfo SerialPortI;
|
||||
private readonly SerialPort _serialPort;
|
||||
|
||||
public OpenShockSerial(SerialPortInfo serialPortI, string apiKey, string endpoint = "https://api.shocklink.net", ILogger? logger = null) : base(DeviceApi.OpenShockSerial, apiKey, endpoint, logger)
|
||||
public OpenShockSerial(SerialPortInfo serialPortI, string apiKey, string? endpoint = null, ILogger? logger = null) : base(DeviceApi.OpenShockSerial, apiKey, endpoint??DefaultEndpoint, logger)
|
||||
{
|
||||
this.SerialPortI = serialPortI;
|
||||
this._serialPort = new SerialPort(serialPortI.PortName, BaudRate);
|
||||
|
@ -10,21 +10,15 @@ public abstract class Api : IDisposable
|
||||
// ReSharper disable 4 times MemberCanBePrivate.Global -> Exposed
|
||||
protected ILogger? Logger;
|
||||
public readonly DeviceApi ApiType;
|
||||
private readonly Queue<ValueTuple<ControlAction, Shocker, int, int>> _queue = new();
|
||||
private bool _workOnQueue = true;
|
||||
private Queue<DateTime> order = new();
|
||||
private Dictionary<DateTime, Task> tasks = new();
|
||||
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
|
||||
private readonly Thread _workQueueThread;
|
||||
private const short CommandDelay = 50;
|
||||
internal readonly IntegerRange ValidIntensityRange, ValidDurationRange;
|
||||
|
||||
internal void Control(ControlAction action, int intensity, int duration, params Shocker[] shockers)
|
||||
{
|
||||
bool enqueueItem = true;
|
||||
if (action is ControlAction.Nothing)
|
||||
{
|
||||
this.Logger?.Log(LogLevel.Information, "No action defined.");
|
||||
enqueueItem = false;
|
||||
}
|
||||
if (!ValidIntensityRange.IsValueWithinLimits(intensity))
|
||||
{
|
||||
this.Logger?.Log(LogLevel.Information, $"Value not within allowed {nameof(intensity)}-Range ({ValidIntensityRange.RangeString()}): {intensity}");
|
||||
@ -43,7 +37,12 @@ public abstract class Api : IDisposable
|
||||
foreach (Shocker shocker in shockers)
|
||||
{
|
||||
this.Logger?.Log(LogLevel.Debug, $"Enqueueing {action} Intensity: {intensity} Duration: {duration}\nShocker:\n{shocker}");
|
||||
_queue.Enqueue(new(action, shocker, intensity, duration));
|
||||
ValueTuple<ControlAction, Shocker, int, int> tuple = new(action, shocker, intensity, duration);
|
||||
DateTime now = DateTime.Now;
|
||||
Task t = new (() => ExecuteTask(now, tuple));
|
||||
order.Enqueue(now);
|
||||
tasks.Add(now, t);
|
||||
t.Start();
|
||||
}
|
||||
}
|
||||
|
||||
@ -55,19 +54,17 @@ public abstract class Api : IDisposable
|
||||
this.Logger = logger;
|
||||
this.ValidIntensityRange = validIntensityRange;
|
||||
this.ValidDurationRange = validDurationRange;
|
||||
this._workQueueThread = new Thread(QueueThread);
|
||||
this._workQueueThread.Start();
|
||||
}
|
||||
|
||||
private void QueueThread()
|
||||
private void ExecuteTask(DateTime when, ValueTuple<ControlAction, Shocker, int, int> tuple)
|
||||
{
|
||||
while (_workOnQueue)
|
||||
if (_queue.Count > 0 && _queue.Dequeue() is { } action)
|
||||
{
|
||||
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);
|
||||
Thread.Sleep(action.Item4 + CommandDelay);
|
||||
}
|
||||
while (order.First() != when)
|
||||
Thread.Sleep(CommandDelay);
|
||||
this.Logger?.Log(LogLevel.Information, $"Executing: {Enum.GetName(tuple.Item1)} Intensity: {tuple.Item3} Duration: {tuple.Item4}\nShocker:\n{tuple.Item2}");
|
||||
ControlInternal(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4);
|
||||
Thread.Sleep(tuple.Item4);
|
||||
tasks.Remove(when);
|
||||
order.Dequeue();
|
||||
}
|
||||
|
||||
public void SetLogger(ILogger? logger)
|
||||
@ -97,6 +94,7 @@ public abstract class Api : IDisposable
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_workOnQueue = false;
|
||||
foreach ((DateTime when, Task? task) in tasks)
|
||||
task?.Dispose();
|
||||
}
|
||||
}
|
@ -11,7 +11,7 @@ public abstract class OpenShockApi : Api
|
||||
// ReSharper disable twice MemberCanBeProtected.Global -> Exposed
|
||||
public string Endpoint { get; init; }
|
||||
public string ApiKey { get; init; }
|
||||
private const string DefaultEndpoint = "https://api.shocklink.net";
|
||||
public const string DefaultEndpoint = "https://api.openshock.app";
|
||||
|
||||
// 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)
|
||||
|
@ -8,22 +8,43 @@ namespace CShocker.Devices.Additional;
|
||||
|
||||
public static class ApiHttpClient
|
||||
{
|
||||
internal static HttpResponseMessage MakeAPICall(HttpMethod method, string uri, string? jsonContent, ILogger? logger = null, params ValueTuple<string, string>[] customHeaders)
|
||||
private static readonly ProductInfoHeaderValue UserAgent = GetUserAgent();
|
||||
|
||||
private static ProductInfoHeaderValue GetUserAgent()
|
||||
{
|
||||
Assembly assembly = Assembly.GetExecutingAssembly();
|
||||
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
|
||||
ProductInfoHeaderValue userAgent = new (fvi.ProductName ?? fvi.FileName, fvi.ProductVersion);
|
||||
FileVersionInfo fvi;
|
||||
if (assembly.Location == String.Empty)
|
||||
{
|
||||
DirectoryInfo dir = new (AppContext.BaseDirectory);
|
||||
FileInfo? f = dir.GetFiles("*.exe").FirstOrDefault();
|
||||
if (f is null)
|
||||
return new("CShocker", "Release");
|
||||
fvi = FileVersionInfo.GetVersionInfo(f.FullName);
|
||||
}
|
||||
else
|
||||
{
|
||||
fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
|
||||
}
|
||||
return new (fvi.ProductName ?? fvi.FileName, fvi.ProductVersion);
|
||||
}
|
||||
|
||||
internal static HttpResponseMessage MakeAPICall(HttpMethod method, string uri, string? jsonContent, ILogger? logger = null, params ValueTuple<string, string>[] customHeaders)
|
||||
{
|
||||
HttpRequestMessage request = new (method, uri)
|
||||
{
|
||||
Headers =
|
||||
{
|
||||
UserAgent = { userAgent },
|
||||
Accept = { new MediaTypeWithQualityHeaderValue("application/json") }
|
||||
UserAgent = { UserAgent },
|
||||
Accept = { new MediaTypeWithQualityHeaderValue("application/json") },
|
||||
|
||||
}
|
||||
};
|
||||
if (jsonContent is not null && jsonContent.Length > 0)
|
||||
request.Content =
|
||||
new StringContent(jsonContent, Encoding.UTF8, new MediaTypeHeaderValue("application/json"));
|
||||
request.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(jsonContent))
|
||||
{
|
||||
Headers = { ContentType = MediaTypeHeaderValue.Parse("application/json") }
|
||||
};
|
||||
foreach ((string, string) customHeader in customHeaders)
|
||||
request.Headers.Add(customHeader.Item1, customHeader.Item2);
|
||||
logger?.Log(LogLevel.Debug, string.Join("\n\t",
|
||||
@ -35,10 +56,10 @@ public static class ApiHttpClient
|
||||
HttpClient httpClient = new();
|
||||
HttpResponseMessage response = httpClient.Send(request);
|
||||
logger?.Log(!response.IsSuccessStatusCode ? LogLevel.Error : LogLevel.Debug, string.Join("\n\t",
|
||||
"Request:",
|
||||
"Response:",
|
||||
$"\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}"));
|
||||
$"\u2514\u2500\u2500 Content: {response.Content.ReadAsStringAsync().Result}"));
|
||||
httpClient.Dispose();
|
||||
return response;
|
||||
}
|
||||
|
@ -5,5 +5,5 @@ public enum ControlAction
|
||||
Beep,
|
||||
Vibrate,
|
||||
Shock,
|
||||
Nothing
|
||||
Stop
|
||||
}
|
@ -14,7 +14,7 @@ public class ShockerJsonConverter : JsonConverter
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
|
||||
{
|
||||
JObject jo = JObject.Load(reader);
|
||||
if (jo.ContainsKey("model")) //OpenShockShocker
|
||||
if (jo.ContainsKey("Model")) //OpenShockShocker
|
||||
{
|
||||
return jo.ToObject<OpenShockShocker>(serializer)!;
|
||||
}
|
||||
|
@ -3,7 +3,6 @@ using CShocker.Devices.APIs;
|
||||
using CShocker.Shockers;
|
||||
using GlaxLogger;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
Logger logger = new (LogLevel.Trace);
|
||||
|
||||
@ -14,16 +13,22 @@ while(apiKey is null || apiKey.Length < 1)
|
||||
|
||||
|
||||
OpenShockHttp openShockHttp = new (apiKey, logger: logger);
|
||||
OpenShockShocker shocker = openShockHttp.GetShockers().First();
|
||||
foreach (OpenShockShocker shocker in openShockHttp.GetShockers())
|
||||
{
|
||||
shocker.Control(ControlAction.Vibrate, 20, 1000);
|
||||
shocker.Control(ControlAction.Vibrate, 20, 1000);
|
||||
shocker.Control(ControlAction.Vibrate, 20, 1000);
|
||||
Thread.Sleep(1100);
|
||||
}
|
||||
|
||||
/*
|
||||
File.WriteAllText("shockers.json", JsonConvert.SerializeObject(shocker));
|
||||
OpenShockShocker deserialized = JsonConvert.DeserializeObject<OpenShockShocker>(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
|
||||
@ -53,4 +58,5 @@ shocker.Dispose();
|
||||
deserialized.Dispose();
|
||||
*/
|
||||
|
||||
logger.Dispose();
|
||||
while(!Console.KeyAvailable)
|
||||
Thread.Sleep(100);
|
@ -2,9 +2,10 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
|
||||
<LangVersion>latestmajor</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@ -12,7 +13,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="GlaxLogger" Version="1.0.6" />
|
||||
<PackageReference Include="GlaxLogger" Version="1.0.7.2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
Reference in New Issue
Block a user