Compare commits

...

28 Commits

Author SHA1 Message Date
ffb8592972 Fix export of ShockerActions to Json
Update Dependencies
2024-11-03 01:24:19 +01:00
2d429fcb6b fixes 2024-11-03 00:22:25 +01:00
c6bd342e87 Merge remote-tracking branch 'origin/master' 2024-02-12 01:37:32 +01:00
82e14c8b9e Use do-while instead of convoluted setups. 2024-02-12 01:37:28 +01:00
3fe43b6e63 Use do-while instead of convoluted setups. 2024-02-12 01:23:44 +01:00
4c7a3c9069 Serial only on Windows check 2024-02-12 01:23:07 +01:00
fcb5bf0a68 Cleanup 2024-02-12 01:22:46 +01:00
3659e357f2 Dependency Update
Less convoluted json.
2024-02-11 23:38:04 +01:00
eb732aad13 Update Dependency GlaxLogger 2024-02-10 20:56:06 +01:00
66afd442da Update Dependencies 2024-02-10 20:50:44 +01:00
2182e08f5e Log 2024-02-10 20:41:23 +01:00
3871fbc76e Update dependencies 2024-02-04 17:50:10 +01:00
2bd2e5ba0a Add Open Shock Serial 2024-01-20 21:41:47 +01:00
d59543297a Update README.md 2024-01-19 03:14:53 +01:00
92cc79f707 Improved Setup
Update Dependency
2024-01-19 03:08:03 +01:00
6778375f43 Fix Dependency 2024-01-19 02:22:17 +01:00
0dcee037fc Update Readme 2024-01-19 02:22:12 +01:00
ee0ca69475 Fix wrong order of parameters 2024-01-19 02:13:25 +01:00
18d3b6bf66 Update Dependency Cshocker
Update Dependency CS2GSI
Update README
OpenShock now automatically gets shockerIds
2024-01-19 02:06:26 +01:00
d040995051 Dictionary 2024-01-19 01:55:21 +01:00
dbb0bcd89f ConfigurationValid() tobeimplemented 2024-01-19 01:55:15 +01:00
968c3a5c37 Add PiShockHttp 2024-01-19 01:43:04 +01:00
4039455bfd Update Dependecy CShocker 2024-01-19 01:42:47 +01:00
b196f62111 Update Readme... 2024-01-18 18:16:50 +01:00
b085de2b39 Update Readme 2024-01-18 18:16:10 +01:00
ba8b76bfba Update Readme 2024-01-18 18:15:11 +01:00
0f62e9e9c9 Fix setup 2024-01-18 00:21:51 +01:00
41a433bf3f Version 3:
CS2GSI and CShocker libraries
More extensive options for Events
Setup on first start
2024-01-18 00:06:39 +01:00
15 changed files with 522 additions and 343 deletions

View File

@ -4,5 +4,8 @@
<s:Boolean x:Key="/Default/UserDictionary/Words/=appmanifest/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=freezetime/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=libraryfolders/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=NYAA/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=OpenCS2hock/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Sharecode/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=steamapps/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=steamid/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@ -1,3 +1,11 @@
<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_005CCShocker_005CCShocker_005Cbin_005CDebug_005Cnet7_002E0_005CCShocker_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/AddReferences/RecentPaths/=C_003A_005CUsers_005CGlax_005CRiderProjects_005CCShocker_005CCShocker_005Cbin_005CRelease_005Cnet7_002E0_005Cpublish_005CCShocker_002Edll/@EntryIndexedValue">True</s:Boolean>
<s:String x:Key="/Default/Environment/AssemblyExplorer/XmlDocument/@EntryValue">&lt;AssemblyExplorer&gt;&#xD;
&lt;Assembly Path="C:\Users\Glax\RiderProjects\CShocker\CShocker\bin\Debug\net7.0\CShocker.dll" /&gt;&#xD;
&lt;/AssemblyExplorer&gt;</s:String>
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=b6376c03_002D06ba_002D424d_002Db00f_002Dbee38277f47a/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" Name="All tests from Solution" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
&lt;Solution /&gt;&#xD;
&lt;/SessionState&gt;</s:String>
<s:Boolean x:Key="/Default/ResxEditorPersonal/Initialized/@EntryValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@ -0,0 +1,59 @@
using CShocker.Devices.Abstract;
using CShocker.Devices.Additional;
using CShocker.Shockers.Abstract;
using CShocker.Shockers.Additional;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace OpenCS2hock;
public struct Configuration
{
public LogLevel LogLevel = LogLevel.Information;
public List<ShockerAction> ShockerActions { get; init; }
public List<Api> Apis { get; init; }
public Dictionary<int, Shocker> Shockers { get; init; }
public Configuration()
{
ShockerActions = new ();
Apis = new();
Shockers = new();
}
public override string ToString()
{
return $"Loglevel: {Enum.GetName(typeof(LogLevel), LogLevel)}\n" +
$"Apis:\n{string.Join("\n---\n", Apis)}\n" +
$"Shockers:\n{string.Join("\n---\n", Shockers)}\n" +
$"Actions:\n{string.Join("\n---\n", ShockerActions)}\n";
}
internal static Configuration GetConfigurationFromFile(string? path = null, ILogger? logger = null)
{
string settingsFilePath = path ?? "config.json";
Configuration c;
if (!File.Exists(settingsFilePath))
c = Setup.Run().SaveConfiguration();
else
c = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText(settingsFilePath), new ApiJsonConverter(), new ShockerJsonConverter());
if (!c.ConfigurationValid())
throw new Exception("Configuration validation failed.");
return c;
}
internal Configuration SaveConfiguration(string? path = null)
{
string settingsFilePath = path ?? "config.json";
File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(this, Formatting.Indented));
return this;
}
private bool ConfigurationValid()
{
return true; //TODO Check values
}
}

View File

@ -1,17 +0,0 @@
namespace OpenCS2hock;
internal class ConfiguredInteger
{
private readonly int _min, _max;
internal ConfiguredInteger(int min = 0, int max = 50)
{
this._min = min;
this._max = max;
}
internal int GetValue()
{
return Random.Shared.Next(_min, _max);
}
}

View File

@ -1,27 +0,0 @@
using Microsoft.Win32;
using Newtonsoft.Json;
namespace OpenCS2hock;
public static class Installer
{
internal static Settings GetSettings(string? path = null)
{
string settingsFilePath = path ?? "config.json";
if (!File.Exists(settingsFilePath))
File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(new Settings(), Formatting.Indented));
return JsonConvert.DeserializeObject<Settings>(File.ReadAllText(settingsFilePath));
}
internal static List<Shocker> GetShockers(Settings settings, Logger? logger = null)
{
List<Shocker> shockers = new();
shockers.Add(new OpenShock(settings.OpenShockSettings.Endpoint, settings.OpenShockSettings.ApiKey,
settings.OpenShockSettings.Shockers,
new ConfiguredInteger(settings.IntensityRange.Min, settings.IntensityRange.Max),
new ConfiguredInteger(settings.DurationRange.Min, settings.DurationRange.Max),
logger));
return shockers;
}
}

View File

@ -1,65 +0,0 @@
using Microsoft.Extensions.Logging;
namespace OpenCS2hock;
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<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> 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>(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
};
}
}

View File

@ -1,25 +1,28 @@
using Microsoft.Extensions.Logging;
using CS2GSI;
using GlaxLogger;
using CS2Event = CS2GSI.CS2Event;
namespace OpenCS2hock;
// ReSharper disable once InconsistentNaming
public class OpenCS2hock
{
private readonly CS2GSI.CS2GSI _cs2GSI;
private readonly List<Shocker> _shockers;
private readonly Settings _settings;
private readonly Configuration _configuration;
private readonly Logger? _logger;
public OpenCS2hock(string? settingsPath = null, Logger? logger = null)
public OpenCS2hock(string? configPath = null, bool editConfig = false, Logger? logger = null)
{
this._logger = logger;
this._logger?.Log(LogLevel.Information, "Starting OpenCS2hock...");
this._logger?.Log(LogLevel.Information, "Loading Settings...");
_settings = Installer.GetSettings(settingsPath);
this._logger?.Log(LogLevel.Information, $"Loglevel set to {_settings.LogLevel}");
this._logger?.UpdateLogLevel(_settings.LogLevel);
this._logger?.Log(LogLevel.Information, _settings.ToString());
this._logger?.Log(LogLevel.Information, "Setting up Shockers...");
this._shockers = Installer.GetShockers(_settings, logger);
this._logger?.Log(LogLevel.Information, "Loading Configuration...");
this._configuration = Configuration.GetConfigurationFromFile(configPath, this._logger);
if(editConfig)
Setup.EditConfig(ref this._configuration);
this._logger?.Log(LogLevel.Information, $"Loglevel set to {_configuration.LogLevel}");
this._logger?.UpdateLogLevel(_configuration.LogLevel);
this._logger?.Log(LogLevel.Information, _configuration.ToString());
this._cs2GSI = new CS2GSI.CS2GSI(_logger);
this.SetupEventHandlers();
while(this._cs2GSI.IsRunning)
@ -29,44 +32,45 @@ public class OpenCS2hock
private void SetupEventHandlers()
{
this._logger?.Log(LogLevel.Information, "Setting up EventHandlers...");
foreach (Shocker shocker in this._shockers)
foreach (ShockerAction shockerAction in this._configuration.ShockerActions)
{
foreach (KeyValuePair<string, string> kv in _settings.Actions)
{
switch (kv.Key)
switch (shockerAction.TriggerEvent)
{
case "OnKill":
this._cs2GSI.OnKill += (cs2EventArgs) => shocker.Control(Settings.StringToAction(kv.Value));
break;
case "OnDeath":
this._cs2GSI.OnDeath += (cs2EventArgs) => shocker.Control(Settings.StringToAction(kv.Value));
break;
case "OnRoundStart":
this._cs2GSI.OnRoundStart += (cs2EventArgs) => shocker.Control(Settings.StringToAction(kv.Value));
break;
case "OnRoundEnd":
this._cs2GSI.OnRoundOver += (cs2EventArgs) => shocker.Control(Settings.StringToAction(kv.Value));
break;
case "OnRoundLoss":
this._cs2GSI.OnRoundLoss += (cs2EventArgs) => shocker.Control(Settings.StringToAction(kv.Value));
break;
case "OnRoundWin":
this._cs2GSI.OnRoundWin += (cs2EventArgs) => shocker.Control(Settings.StringToAction(kv.Value));
break;
case "OnDamageTaken":
this._cs2GSI.OnDamageTaken += (cs2EventArgs) =>
shocker.Control(Settings.StringToAction(kv.Value),
intensity: MapInt(cs2EventArgs.ValueAsOrDefault<int>(), 0, 100,
_settings.IntensityRange.Min, _settings.IntensityRange.Max));
break;
case CS2Event.OnKill: this._cs2GSI.OnKill += args => EventHandler(args, shockerAction); break;
case CS2Event.OnHeadshot: this._cs2GSI.OnHeadshot += args => EventHandler(args, shockerAction); break;
case CS2Event.OnDeath: this._cs2GSI.OnDeath += args => EventHandler(args, shockerAction); break;
case CS2Event.OnFlashed: this._cs2GSI.OnFlashed += args => EventHandler(args, shockerAction); break;
case CS2Event.OnBurning: this._cs2GSI.OnBurning += args => EventHandler(args, shockerAction); break;
case CS2Event.OnSmoked: this._cs2GSI.OnSmoked += args => EventHandler(args, shockerAction); break;
case CS2Event.OnRoundStart: this._cs2GSI.OnRoundStart += args => EventHandler(args,shockerAction); break;
case CS2Event.OnRoundOver: this._cs2GSI.OnRoundOver += args => EventHandler(args, shockerAction); break;
case CS2Event.OnRoundWin: this._cs2GSI.OnRoundWin += args => EventHandler(args, shockerAction); break;
case CS2Event.OnRoundLoss: this._cs2GSI.OnRoundLoss += args => EventHandler(args, shockerAction); break;
case CS2Event.OnDamageTaken: this._cs2GSI.OnDamageTaken += args => EventHandler(args, shockerAction); break;
case CS2Event.OnMatchStart: this._cs2GSI.OnMatchStart += args => EventHandler(args, shockerAction); break;
case CS2Event.OnMatchOver: this._cs2GSI.OnMatchOver += args => EventHandler(args, shockerAction); break;
case CS2Event.OnMoneyChange: this._cs2GSI.OnMoneyChange += args => EventHandler(args, shockerAction); break;
case CS2Event.OnHealthChange: this._cs2GSI.OnHealthChange += args => EventHandler(args, shockerAction); break;
case CS2Event.OnArmorChange: this._cs2GSI.OnArmorChange += args => EventHandler(args, shockerAction); break;
case CS2Event.OnHelmetChange: this._cs2GSI.OnHelmetChange += args => EventHandler(args, shockerAction); break;
case CS2Event.OnEquipmentValueChange: this._cs2GSI.OnEquipmentValueChange += args => EventHandler(args, shockerAction); break;
case CS2Event.OnTeamChange: this._cs2GSI.OnTeamChange += args => EventHandler(args, shockerAction); break;
case CS2Event.OnPlayerChange: this._cs2GSI.OnPlayerChange += args => EventHandler(args, shockerAction); break;
case CS2Event.OnHalfTime: this._cs2GSI.OnHalfTime += args => EventHandler(args, shockerAction); break;
case CS2Event.OnFreezeTime: this._cs2GSI.OnFreezeTime += args => EventHandler(args, shockerAction); break;
case CS2Event.OnBombPlanted: this._cs2GSI.OnBombPlanted += args => EventHandler(args, shockerAction); break;
case CS2Event.OnBombDefused: this._cs2GSI.OnBombDefused += args => EventHandler(args, shockerAction); break;
case CS2Event.OnBombExploded: this._cs2GSI.OnBombExploded += args => EventHandler(args, shockerAction); break;
case CS2Event.AnyEvent: this._cs2GSI.AnyEvent += args => EventHandler(args, shockerAction); break;
case CS2Event.AnyMessage: this._cs2GSI.AnyMessage += args => EventHandler(args, shockerAction); break;
default: this._logger?.Log(LogLevel.Debug, $"CS2Event {nameof(shockerAction.TriggerEvent)} unknown."); break;
}
}
}
}
private int MapInt(int input, int fromLow, int fromHigh, int toLow, int toHigh)
private void EventHandler(CS2EventArgs cs2EventArgs, ShockerAction shockerAction)
{
int mappedValue = (input - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
return mappedValue;
this._logger?.Log(LogLevel.Information, $"Action {shockerAction}\nEventArgs: {cs2EventArgs}");
shockerAction.Execute(_configuration.Shockers, cs2EventArgs);
}
}

View File

@ -6,10 +6,13 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>OpenCS2Hock</RootNamespace>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CS2GSI" Version="1.0.4" />
<PackageReference Include="CS2GSI" Version="1.0.8" />
<PackageReference Include="CShocker" Version="2.5.1" />
<PackageReference Include="GlaxLogger" Version="1.0.7.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

View File

@ -1,45 +0,0 @@
using System.Net.Http.Headers;
using System.Text;
using Microsoft.Extensions.Logging;
namespace OpenCS2hock;
internal class OpenShock : Shocker
{
protected override void ControlInternal(ControlAction action, string shockerId, int intensity, int duration)
{
HttpRequestMessage request = new (HttpMethod.Post, $"{Endpoint}/1/shockers/control")
{
Headers =
{
UserAgent = { new ProductInfoHeaderValue("OpenCS2hock", "1") },
Accept = { new MediaTypeWithQualityHeaderValue("application/json") }
},
Content = new StringContent(@"[ { "+
$"\"id\": \"{shockerId}\"," +
$"\"type\": {ControlActionToByte(action)},"+
$"\"intensity\": {intensity},"+
$"\"duration\": {duration}"+
"}]", Encoding.UTF8, new MediaTypeHeaderValue("application/json"))
};
request.Headers.Add("OpenShockToken", ApiKey);
HttpResponseMessage response = this.HttpClient.Send(request);
this.Logger?.Log(LogLevel.Debug, $"{request.RequestUri} response: {response.StatusCode}");
}
private byte ControlActionToByte(ControlAction action)
{
return action switch
{
ControlAction.Beep => 3,
ControlAction.Vibrate => 2,
ControlAction.Shock => 1,
_ => 0
};
}
internal OpenShock(string endpoint, string apiKey, string[] shockerIds, ConfiguredInteger intensity, ConfiguredInteger duration, Logger? logger = null) : base(endpoint, apiKey, shockerIds, intensity, duration, logger)
{
}
}

View File

@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using GlaxLogger;
using Microsoft.Extensions.Logging;
namespace OpenCS2hock;
@ -6,6 +7,6 @@ public class Program
{
public static void Main(string[] args)
{
OpenCS2hock openCS2Hock = new OpenCS2hock(logger: new Logger(LogLevel.Information));
OpenCS2hock openCS2Hock = new OpenCS2hock(editConfig: true, logger: new Logger(LogLevel.Information));
}
}

View File

@ -1,70 +0,0 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace OpenCS2hock;
public struct Settings
{
public LogLevel LogLevel = LogLevel.Information;
public OpenShockSettings OpenShockSettings = new()
{
Endpoint = "https://api.shocklink.net",
ApiKey = "",
Shockers = Array.Empty<string>()
};
public Range IntensityRange = new ()
{
Min = 20,
Max = 60
};
public Range DurationRange = new()
{
Min = 1000,
Max = 1000
};
public Dictionary<string, string> Actions = new()
{
{"OnKill", "Nothing"},
{"OnDeath", "Shock"},
{"OnRoundStart", "Vibrate"},
{"OnRoundEnd", "Nothing"},
{"OnRoundWin", "Beep"},
{"OnRoundLoss", "Nothing"},
{"OnDamageTaken", "Vibrate"}
};
public Settings()
{
}
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
internal static Shocker.ControlAction StringToAction(string str)
{
return str.ToLower() switch
{
"shock" => Shocker.ControlAction.Shock,
"vibrate" => Shocker.ControlAction.Vibrate,
"beep" => Shocker.ControlAction.Beep,
_ => Shocker.ControlAction.Nothing
};
}
}
public struct OpenShockSettings
{
public string Endpoint, ApiKey;
public string[] Shockers;
}
public struct Range
{
public short Min, Max;
}

263
OpenCS2hock/Setup.cs Normal file
View File

@ -0,0 +1,263 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using CShocker.Devices.Abstract;
using CShocker.Devices.Additional;
using CShocker.Devices.APIs;
using CShocker.Ranges;
using CShocker.Shockers;
using CShocker.Shockers.Abstract;
using Microsoft.Extensions.Logging;
using CS2Event = CS2GSI.CS2Event;
namespace OpenCS2hock;
public static class Setup
{
internal static Configuration Run()
{
Console.Clear();
Console.WriteLine("Running first-time setup.");
Configuration c = new();
AddApisWorkflow(ref c);
Console.Clear();
AddActionsWorkflow(ref c);
return c;
}
internal static void EditConfig(ref Configuration c)
{
ConsoleKey? pressedKey = null;
while (pressedKey is not ConsoleKey.X && pressedKey is not ConsoleKey.Q)
{
Console.Clear();
Console.WriteLine("Config Edit Mode.\n");
Console.WriteLine("1) LogLevel");
Console.WriteLine("2) Add API");
Console.WriteLine("3) Refresh Shockers (OpenShock)");
Console.WriteLine("4) Add Action");
Console.WriteLine("\nq) Quit Edit Mode");
pressedKey = Console.ReadKey().Key;
switch (pressedKey)
{
case ConsoleKey.D1:
string[] levels = Enum.GetNames<LogLevel>();
int selected;
do
{
Console.Clear();
Console.WriteLine("New LogLevel:");
for (int i = 0; i < levels.Length; i++)
Console.WriteLine($"{i}) {levels[i]}");
} while (!int.TryParse(Console.ReadKey().KeyChar.ToString(), out selected) || selected < 0 || selected >= levels.Length);
Console.WriteLine();//NewLine after Input
c.LogLevel = Enum.Parse<LogLevel>(levels[selected]);
break;
case ConsoleKey.D2:
AddApisWorkflow(ref c);
break;
case ConsoleKey.D3:
// ReSharper disable once PossibleInvalidCastExceptionInForeachLoop Only returning OpenShockApi Objects
foreach (OpenShockApi api in c.Apis.Where(a => a is OpenShockApi))
{
Configuration configuration = c;
foreach(OpenShockShocker s in api.GetShockers().Where(s => !configuration.Shockers.ContainsValue(s)))
c.Shockers.Add(c.Shockers.Any() ? c.Shockers.Keys.Max() + 1 : 0, s);
}
break;
case ConsoleKey.D4:
AddActionsWorkflow(ref c);
break;
}
}
c.SaveConfiguration();
}
private static void AddApisWorkflow(ref Configuration c)
{
Console.WriteLine("Adding APIs.");
bool addApis = true;
while (c.Apis.Count < 1 || addApis)
{
Console.Clear();
AddShockerApi(ref c);
Console.WriteLine("Add another Api (Y/N):");
addApis = Console.ReadKey().Key == ConsoleKey.Y;
Console.WriteLine();//NewLine after Input
}
}
private static void AddActionsWorkflow(ref Configuration c)
{
Console.WriteLine("Adding Actions.");
bool addAction = true;
while (c.ShockerActions.Count < 1 || addAction)
{
Console.Clear();
AddAction(ref c);
Console.WriteLine("Add another Action (Y/N):");
addAction = Console.ReadKey().Key == ConsoleKey.Y;
Console.WriteLine();//NewLine after Input
}
}
private static void AddShockerApi(ref Configuration c)
{
Console.WriteLine("Select API:");
Console.WriteLine("1) OpenShock (HTTP)");
Console.WriteLine("2) OpenShock (Serial Windows Only)");
Console.WriteLine("3) PiShock (HTTP) NotImplemented"); //TODO
Console.WriteLine("4) PiShock (Serial Windows Only) NotImplemented"); //TODO
char selectedChar = Console.ReadKey().KeyChar;
int selected;
while (!int.TryParse(selectedChar.ToString(), out selected) || selected < 1 || selected > 4)
selectedChar = Console.ReadKey().KeyChar;
Console.WriteLine();//NewLine after Input
string apiUri, apiKey;
Api? api = null;
switch (selected)
{
case 1: //OpenShock (HTTP)
apiUri = QueryString($"OpenShock API-Endpoint ({OpenShockApi.DefaultEndpoint}):", OpenShockApi.DefaultEndpoint);
apiKey = QueryString("OpenShock API-Key:","");
api = new OpenShockHttp(apiKey, apiUri);
foreach(OpenShockShocker shocker in ((OpenShockHttp)api).GetShockers())
c.Shockers.Add(c.Shockers.Any() ? c.Shockers.Keys.Max() + 1 : 0, shocker);
goto default;
case 2: //OpenShock (Serial)
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
throw new PlatformNotSupportedException("Serial is only supported on Windows.");
apiUri = QueryString($"OpenShock API-Endpoint ({OpenShockApi.DefaultEndpoint}):", OpenShockApi.DefaultEndpoint);
apiKey = QueryString("OpenShock API-Key:","");
SerialPortInfo serialPort = SelectSerialPort();
api = new OpenShockSerial(serialPort, apiKey, apiUri);
foreach (OpenShockShocker shocker in ((OpenShockSerial)api).GetShockers())
c.Shockers.Add(c.Shockers.Any() ? c.Shockers.Keys.Max() + 1 : 0, shocker);
goto default;
case 3: //PiShock (HTTP)
goto default;
case 4: //PiShock (Serial)
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
throw new PlatformNotSupportedException("Serial is only supported on Windows.");
goto default;
default:
if (api is null)
throw new NotImplementedException();
c.Apis.Add(api);
break;
}
}
[SupportedOSPlatform("windows")]
private static SerialPortInfo SelectSerialPort()
{
List<SerialPortInfo> serialPorts = SerialHelper.GetSerialPorts();
int selectedPort;
do
{
Console.Clear();
for(int i = 0; i < serialPorts.Count; i++)
Console.WriteLine($"{i}) {serialPorts[i]}");
Console.WriteLine($"Select Serial Port [0-{serialPorts.Count-1}]:");
} while (!int.TryParse(Console.ReadLine(), out selectedPort) || selectedPort < 0 || selectedPort >= serialPorts.Count);
Console.WriteLine();//NewLine after Input
return serialPorts[selectedPort];
}
private static void AddAction(ref Configuration c)
{
CS2Event triggerEvent = GetTrigger();
int shockerId = GetShockerId(c.Shockers);
ControlAction action = GetControlAction();
bool useEventArgsValue = QueryBool("Try using EventArgs to control Intensity (within set limits)?", false);
IntegerRange intensityRange = GetIntegerRange(0, 100, "%");
IntegerRange durationRange = GetIntegerRange(0, 30000, "ms");
c.ShockerActions.Add(new(triggerEvent, shockerId, action, useEventArgsValue, intensityRange, durationRange));
}
private static int GetShockerId(Dictionary<int, Shocker> shockersDict)
{
List<Shocker> shockers = shockersDict.Values.ToList();
int selectedShockerIndex;
do
{
Console.Clear();
Console.WriteLine("Select Shocker:");
for (int i = 0; i < shockers.Count; i++)
Console.WriteLine($"{i}) {shockers[i]}");
} while (!int.TryParse(Console.ReadLine(), out selectedShockerIndex) || selectedShockerIndex < 0 || selectedShockerIndex > shockersDict.Count);
Console.WriteLine();//NewLine after Input
Shocker shocker = shockers[selectedShockerIndex];
return shockersDict.First(s => s.Value == shocker).Key;
}
private static IntegerRange GetIntegerRange(int min, int max, string? unit = null)
{
Regex rangeRex = new (@"([0-9]{1,5})\-([0-9]{1,5})");
string intensityRangeStr;
do
{
intensityRangeStr = QueryString($"Range ({min}-{max}) {(unit is null ? "" : $"in {unit}")}:", "0-100");
} while (!rangeRex.IsMatch(intensityRangeStr));
return new IntegerRange(short.Parse(rangeRex.Match(intensityRangeStr).Groups[1].Value), short.Parse(rangeRex.Match(intensityRangeStr).Groups[2].Value));
}
private static CS2Event GetTrigger()
{
string[] eventNames = Enum.GetNames(typeof(CS2Event));
int selectedIndex;
do
{
Console.Clear();
Console.WriteLine("Select CS2 Trigger-Event:");
for (int i = 0; i < eventNames.Length; i++)
Console.WriteLine($"{i}) {eventNames[i]}");
} while (!int.TryParse(Console.ReadLine(), out selectedIndex) || selectedIndex < 0 || selectedIndex >= eventNames.Length);
return Enum.Parse<CS2Event>(eventNames[selectedIndex]);
}
private static ControlAction GetControlAction()
{
string[] actionNames = Enum.GetNames(typeof(ControlAction));
int selectedIndex;
do
{
Console.Clear();
Console.WriteLine("Select Action:");
for (int i = 0; i < actionNames.Length; i++)
Console.WriteLine($"{i}) {actionNames[i]}");
} while (!int.TryParse(Console.ReadLine(), out selectedIndex) || selectedIndex < 0 || selectedIndex >= actionNames.Length);
return Enum.Parse<ControlAction>(actionNames[selectedIndex]);
}
private static bool QueryBool(string queryString, bool defaultResult)
{
Console.WriteLine(queryString);
char userInput = Console.ReadKey().KeyChar;
Console.WriteLine();//NewLine after Input
return bool.TryParse(userInput.ToString(), out bool ret) ? ret : defaultResult;
}
private static string QueryString(string queryString, string defaultResult)
{
Console.WriteLine(queryString);
string? userInput = Console.ReadLine();
return userInput?.Length > 0 ? userInput : defaultResult;
}
}

View File

@ -1,41 +0,0 @@
using Microsoft.Extensions.Logging;
namespace OpenCS2hock;
internal abstract class Shocker
{
protected readonly HttpClient HttpClient;
protected readonly string ApiKey,Endpoint;
private readonly string[] _shockerIds;
private readonly ConfiguredInteger _intensity, _duration;
protected readonly Logger? Logger;
internal enum ControlAction { Beep, Vibrate, Shock, Nothing }
internal void Control(ControlAction action, string? shockerId = null, int? intensity = null, int? duration = null)
{
int i = intensity ?? _intensity.GetValue();
int d = duration ?? _duration.GetValue();
this.Logger?.Log(LogLevel.Information, $"{action} {(intensity is not null ? "Overwrite " : "")}{i} {(duration is not null ? "Overwrite " : "")}{d}");
if (action is ControlAction.Nothing)
return;
if(shockerId is null)
foreach (string shocker in _shockerIds)
ControlInternal(action, shocker, i, d);
else
ControlInternal(action, shockerId, i, d);
}
protected abstract void ControlInternal(ControlAction action, string shockerId, int intensity, int duration);
protected Shocker(string endpoint, string apiKey, string[] shockerIds, ConfiguredInteger intensity, ConfiguredInteger duration, Logger? logger = null)
{
this.Endpoint = endpoint;
this.ApiKey = apiKey;
this.HttpClient = new HttpClient();
this._shockerIds = shockerIds;
this._intensity = intensity;
this._duration = duration;
this.Logger = logger;
}
}

View File

@ -0,0 +1,59 @@
using CS2GSI;
using CShocker.Devices.Additional;
using CShocker.Ranges;
using CShocker.Shockers.Abstract;
namespace OpenCS2hock;
public struct ShockerAction
{
public CS2Event TriggerEvent;
// ReSharper disable MemberCanBePrivate.Global -> exposed
public int ShockerId;
public ControlAction Action;
public bool ValueFromInput;
public IntegerRange IntensityRange, DurationRange;
public ShockerAction(CS2Event trigger, int shockerId, ControlAction action, bool valueFromInput, IntegerRange intensityRange, IntegerRange durationRange)
{
this.TriggerEvent = trigger;
this.ShockerId = shockerId;
this.Action = action;
this.ValueFromInput = valueFromInput;
this.IntensityRange = intensityRange;
this.DurationRange = durationRange;
}
public void Execute(Dictionary<int, Shocker> shockers, CS2EventArgs cs2EventArgs)
{
if (!shockers.ContainsKey(ShockerId))
return;
int intensity = ValueFromInput ? IntensityFromCS2Event(cs2EventArgs) : IntensityRange.RandomValueWithinLimits();
int duration = DurationRange.RandomValueWithinLimits();
shockers[ShockerId].Control(Action, intensity, duration);
}
private int IntensityFromCS2Event(CS2EventArgs cs2EventArgs)
{
return TriggerEvent switch
{
CS2Event.OnDamageTaken => MapInt(cs2EventArgs.ValueAsOrDefault<int>(), 0, 100, IntensityRange.Min, IntensityRange.Max),
CS2Event.OnArmorChange => MapInt(cs2EventArgs.ValueAsOrDefault<int>(), 0, 100, IntensityRange.Min, IntensityRange.Max),
_ => IntensityRange.RandomValueWithinLimits()
};
}
private int MapInt(int input, int fromLow, int fromHigh, int toLow, int toHigh)
{
int mappedValue = (input - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
return mappedValue;
}
public override string ToString()
{
return $"Trigger Event: {Enum.GetName(typeof(CS2Event), this.TriggerEvent)}\n" +
$"ShockerId: {ShockerId}\n" +
$"Action: {Enum.GetName(typeof(ControlAction), this.Action)}\n" +
$"ValueFromInput: {ValueFromInput}";
}
}

110
README.md
View File

@ -2,7 +2,7 @@
![GitHub License](https://img.shields.io/github/license/c9glax/OpenCS2hock)
![GitHub Release](https://img.shields.io/github/v/release/c9glax/OpenCS2hock)
Electrifying your Counter-Strike experience. With [OpenShock](https://openshock.org/)!
Electrifying your Counter-Strike experience. With [OpenShock](https://openshock.org/) and [PiShock](https://pishock.com/#/)! (Not Associated)
## How to use
@ -12,49 +12,93 @@ Example `config.json`. Place next to executable. Will also be generated on first
```json
{
"LogLevel": 2,
"OpenShockSettings": {
"Endpoint": "https://api.shocklink.net",
"ApiKey": "<Your Shocklink API Key>",
"Shockers": [ "<Shocker Id> comma seperated" ]
},
"IntensityRange": {
"Min": 30,
"Max": 60
},
"DurationRange": {
"Min": 1000,
"Max": 1000
},
"Actions": {
"OnKill": "Nothing",
"OnDeath": "Shock",
"OnRoundStart": "Nothing",
"OnRoundEnd": "Vibrate",
"OnRoundWin": "Nothing",
"OnRoundLoss": "Shock",
"OnDamageTaken": "Vibrate"
}
"Shockers": [
{
"ShockerIds": [
"ID HERE"
],
"IntensityRange": {
"Min": 30,
"Max": 50
},
"DurationRange": {
"Min": 1000,
"Max": 1000
},
"ApiType": 0,
"Endpoint": "https://api.shocklink.net",
"ApiKey": "API KEY HERE"
}
],
"ShockerActions": [
{
"TriggerEvent": 2,
"ShockerIds": [
"SAME ID HERE"
],
"Action": 2,
"ValueFromInput": false
}
]
}
```
## LogLevel
[Levels](https://learn.microsoft.com/de-de/dotnet/api/microsoft.extensions.logging.loglevel?view=dotnet-plat-ext-8.0)
## Shockers
### ApiKey
For OpenShock get token [here](https://shocklink.net/#/dashboard/tokens)
- For OpenShock (HTTP) get token [here](https://shocklink.net/#/dashboard/tokens)
- For PiShock (HTTP) get information [here](https://apidocs.pishock.com/#header-authenticating)
### Shockers
List of Shocker-Ids, comma seperated. Get Id [here](https://shocklink.net/#/dashboard/shockers/own). Press the three dots -> Edit
### ApiType
CShocker [![Github](https://img.shields.io/badge/Github-8A2BE2)](https://github.com/C9Glax/cshocker) [here](https://github.com/C9Glax/CShocker/blob/master/CShocker/Shockers/Abstract/ShockerApi.cs)
Example `[ "ID-1", "ID-2" ]`
### ShockerIds
List of Shocker-Ids, comma seperated.
`[ "ID-1-asdasd", "ID-2-fghfgh" ]`
### Intensity Range
`0-100`%
in percent
`0-100`
### Duration Range
in ms
- `0-30000` OpenShock
- `0-15000` PiShock
### Values for `Actions`
- Beep
- Shock
- Vibrate
### Username (PiShockHttp only)
For PiShock (HTTP) get information [here](https://apidocs.pishock.com/#header-authenticating)
# Using [CS2GSI](https://github.com/C9Glax/CS2GSI)
### Sharecode (PiShockHttp only)
For PiShock (HTTP) get information [here](https://apidocs.pishock.com/#header-authenticating)
## ShockerActions
### TriggerEvent IDs
From CS2GSI [![Github](https://img.shields.io/badge/Github-8A2BE2)](https://github.com/C9Glax/CS2GSI) [here](https://github.com/C9Glax/CS2GSI/blob/master/CS2GSI/CS2Event.cs)
### ShockerIds
List of Shocker-Ids, comma seperated. (Same as in configured Shocker)
`[ "ID-1", "ID-2" ]`
### Actions
From CShocker [![Github](https://img.shields.io/badge/Github-8A2BE2)](https://github.com/C9Glax/cshocker) [here](https://github.com/C9Glax/CShocker/blob/master/CShocker/Shockers/ControlAction.cs)
### ValueFromInput
Use CS2GSI EventArgs value to determine Intensity (within configured IntensityRange)
# Using
### CS2GSI
[![GitHub License](https://img.shields.io/github/license/c9glax/CS2GSI)](https://img.shields.io/github/license/c9glax/CS2GSI/LICENSE)
[![NuGet Version](https://img.shields.io/nuget/v/CS2GSI)](https://www.nuget.org/packages/CS2GSI/)
[![Github](https://img.shields.io/badge/Github-8A2BE2)](https://github.com/C9Glax/CS2GSI)
[![GitHub Release](https://img.shields.io/github/v/release/c9glax/CS2GSI)](https://github.com/C9Glax/CS2GSI/releases/latest)
### CShocker
[![GitHub License](https://img.shields.io/github/license/c9glax/cshocker)](https://github.com/C9Glax/CShocker)
[![Github](https://img.shields.io/badge/Github-8A2BE2)](https://github.com/C9Glax/cshocker)
[![NuGet Version](https://img.shields.io/nuget/v/CShocker)](https://shields.io/badges/nu-get-version)