16 Commits

Author SHA1 Message Date
8cca25266a Changed access-types 2024-01-14 02:12:45 +01:00
54c82c93e2 Changed default IntensityRange to 20-60 2024-01-14 02:10:37 +01:00
8526c6b00b Only handle events of own steamid 2024-01-14 02:10:24 +01:00
f77f5bc3b4 Add "Over" Roundstate 2024-01-14 02:09:54 +01:00
5824e24748 gsi.cfg timeout, buffer, throttle changes 2024-01-14 02:09:40 +01:00
45eea0c7c5 Do nothing when action is nothing 2024-01-14 01:13:09 +01:00
671fdc5314 Working 2024-01-14 01:10:58 +01:00
66f234e19a Fixed Auth for OpenShock 2024-01-14 01:10:52 +01:00
0303efac16 Corrected json parsing for messagehandling 2024-01-14 01:10:36 +01:00
47b721d419 Settings ToString 2024-01-14 01:04:55 +01:00
d102c970ec Output always what is could happen 2024-01-14 01:04:46 +01:00
850d9c842b Fix Missing Directory 2024-01-14 00:42:14 +01:00
ceb7fb087c Adjusted default values. 2024-01-14 00:42:05 +01:00
bc43aba60e Generalized implementation and added log for Shockers 2024-01-14 00:37:52 +01:00
c418bb0460 Cleanup 2024-01-14 00:32:05 +01:00
bd41858a17 Write CS2 Events to seperate directory 2024-01-14 00:30:59 +01:00
9 changed files with 98 additions and 75 deletions

View File

@ -2,43 +2,49 @@
namespace OpenCS2hock;
public class CS2MessageHandler
internal class CS2MessageHandler
{
public delegate void CS2EventHandler();
public event CS2EventHandler? OnKill;
public event CS2EventHandler? OnDeath;
public event CS2EventHandler? OnRoundStart;
public event CS2EventHandler? OnRoundEnd;
public event CS2EventHandler? OnRoundWin;
public event CS2EventHandler? OnRoundLoss;
internal delegate void CS2EventHandler();
internal event CS2EventHandler? OnKill;
internal event CS2EventHandler? OnDeath;
internal event CS2EventHandler? OnRoundStart;
internal event CS2EventHandler? OnRoundEnd;
internal event CS2EventHandler? OnRoundWin;
internal event CS2EventHandler? OnRoundLoss;
public void HandleCS2Message(string message)
internal void HandleCS2Message(string message, string mySteamId)
{
JObject messageJson = JObject.Parse(message);
string? steamId = messageJson.SelectToken("player.steamid", false)?.Value<string>();
if (steamId is null || steamId != mySteamId)
{
Console.WriteLine("Not my steamid");
return;
}
JToken? previously = messageJson.GetValue("previously");
RoundState currentRoundState = ParseRoundStateFromString(messageJson["round"]?.Value<string>("phase"));
RoundState previousRoundState = ParseRoundStateFromString(previously?["round"]?.Value<string>("phase"));
if(previousRoundState == RoundState.FreezeTime && currentRoundState == RoundState.Live)
RoundState currentRoundState = ParseRoundStateFromString(messageJson.SelectToken("round.phase", false)?.Value<string>());
RoundState previousRoundState = ParseRoundStateFromString(messageJson.SelectToken("previously.round.phase", false)?.Value<string>());
if(previousRoundState == RoundState.Over && currentRoundState == RoundState.Live)
OnRoundStart?.Invoke();
if(previousRoundState == RoundState.Live && currentRoundState == RoundState.FreezeTime)
OnRoundEnd?.Invoke();
if(previousRoundState == RoundState.Live && currentRoundState == RoundState.Over)
OnRoundEnd?.Invoke();
Team playerTeam = ParseTeamFromString(messageJson["player"]?.Value<string>("team"));
Team winnerTeam = ParseTeamFromString(messageJson["round"]?.Value<string>("win_team"));
Team playerTeam = ParseTeamFromString(messageJson.SelectToken("player.team", false)?.Value<string>());
Team winnerTeam = ParseTeamFromString(messageJson.SelectToken("round.win_team", false)?.Value<string>());
if(winnerTeam != Team.None && playerTeam == winnerTeam)
OnRoundWin?.Invoke();
else if(winnerTeam != Team.None && playerTeam != winnerTeam)
OnRoundLoss?.Invoke();
int? previousDeaths = previously?["player"]?["match_stats"]?.Value<int>("deaths");
int? currentDeaths = messageJson["player"]?["match_stats"]?.Value<int>("deaths");
int? previousDeaths = messageJson.SelectToken("previously.player.match_stats.deaths", false)?.Value<int>();
int? currentDeaths = messageJson.SelectToken("player.match_stats.deaths", false)?.Value<int>();
if(currentDeaths > previousDeaths)
OnDeath?.Invoke();
int? previousKills = previously?["player"]?["match_stats"]?.Value<int>("kills");
int? currentKills = messageJson["player"]?["match_stats"]?.Value<int>("kills");
int? previousKills = messageJson.SelectToken("previously.player.match_stats.kills", false)?.Value<int>();
int? currentKills = messageJson.SelectToken("player.match_stats.kills", false)?.Value<int>();
if(currentKills > previousKills)
OnKill?.Invoke();
}
@ -49,6 +55,7 @@ public class CS2MessageHandler
{
"live" => RoundState.Live,
"freezetime" => RoundState.FreezeTime,
"over" => RoundState.Over,
_ => RoundState.Unknown
};
}
@ -63,7 +70,7 @@ public class CS2MessageHandler
};
}
private enum RoundState {FreezeTime, Live, Unknown}
private enum RoundState {FreezeTime, Live, Over, Unknown}
private enum Team {T, CT, None}
}

View File

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

View File

@ -3,16 +3,16 @@ using System.Text;
namespace OpenCS2hock;
public class GSIServer
internal class GSIServer
{
private HttpListener HttpListener { get; init; }
public delegate void OnMessageEventHandler(string content);
public event OnMessageEventHandler? OnMessage;
internal delegate void OnMessageEventHandler(string content);
internal event OnMessageEventHandler? OnMessage;
private bool _keepRunning = true;
public bool IsRunning { get; private set; }
internal bool IsRunning { get; private set; }
public GSIServer(int port)
internal GSIServer(int port)
{
HttpListener = new HttpListener();
HttpListener.Prefixes.Add($"http://127.0.0.1:{port}/");
@ -33,12 +33,11 @@ public class GSIServer
Console.WriteLine($"[{request.HttpMethod}] {request.Url} - {request.UserAgent}");
HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.Accepted);
HttpResponseMessage responseMessage = new (HttpStatusCode.Accepted);
context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(responseMessage.ToString()));
StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding);
StreamReader reader = new (request.InputStream, request.ContentEncoding);
string content = await reader.ReadToEndAsync();
Console.WriteLine(content);
OnMessage?.Invoke(content);
}
HttpListener.Close();

View File

@ -5,7 +5,7 @@ namespace OpenCS2hock;
public static class Installer
{
public static Settings GetSettings(string? path = null)
internal static Settings GetSettings(string? path = null)
{
string settingsFilePath = path ?? "config.json";
if (!File.Exists(settingsFilePath))
@ -14,7 +14,7 @@ public static class Installer
return JsonConvert.DeserializeObject<Settings>(File.ReadAllText(settingsFilePath));
}
public static List<Shocker> GetShockers(Settings settings)
internal static List<Shocker> GetShockers(Settings settings)
{
List<Shocker> shockers = new();
shockers.Add(new OpenShock(settings.OpenShockSettings.Endpoint, settings.OpenShockSettings.ApiKey,
@ -24,13 +24,13 @@ public static class Installer
return shockers;
}
public static void InstallGsi()
internal static void InstallGsi()
{
string installLocation = Path.Combine(GetInstallDirectory(), "game\\csgo\\cfg\\gamestate_integration_opencs2hock.cfg");
File.WriteAllText(installLocation, Resources.GSI_CFG_Content);
}
public static string GetInstallDirectory(int appId = 730)
private static string GetInstallDirectory(int appId = 730)
{
string steamInstallation =
#pragma warning disable CA1416 //Registry only available on Windows

View File

@ -11,9 +11,11 @@ public class OpenCS2hock
{
_settings = Installer.GetSettings(settingsPath);
this._shockers = Installer.GetShockers(_settings);
Console.WriteLine(_settings);
Installer.InstallGsi();
this._cs2MessageHandler = new CS2MessageHandler();
this.SetupEventHandlers();
this.GSIServer = new GSIServer(3000);
this.GSIServer.OnMessage += OnGSIMessage;
@ -59,9 +61,9 @@ public class OpenCS2hock
private void OnGSIMessage(string content)
{
string fileName = Path.Combine(Environment.CurrentDirectory, $"{DateTime.Now.ToLongTimeString().Replace(':','.')}.json");
Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "CS2Events"));
string fileName = Path.Combine(Environment.CurrentDirectory, "CS2Events" ,$"{DateTime.Now.ToLongTimeString().Replace(':','.')}.json");
File.WriteAllText(fileName, content);
Console.WriteLine(fileName);
_cs2MessageHandler.HandleCS2Message(content);
_cs2MessageHandler.HandleCS2Message(content, _settings.SteamId);
}
}

View File

@ -1,36 +1,29 @@
using System.Net.Http.Headers;
using System.Text;
namespace OpenCS2hock;
public class OpenShock : Shocker
internal class OpenShock : Shocker
{
public override void Control(ControlAction action, string? shockerId = null)
{
if(shockerId is null)
foreach(string shocker in ShockerIds)
SendRequestMessage(action, shocker);
else
SendRequestMessage(action, shockerId);
}
private void SendRequestMessage(ControlAction action, string shockerId)
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") },
Authorization = new AuthenticationHeaderValue("Basic", ApiKey)
Accept = { new MediaTypeWithQualityHeaderValue("application/json") }
},
Content = new StringContent(@"[ { "+
$"\"id\": \"{shockerId}\"," +
$"\"type\": {ControlActionToByte(action)},"+
$"\"intensity\": {Intensity.GetValue()},"+
$"\"duration\": {Duration.GetValue()}"+
"}]")
$"\"intensity\": {intensity},"+
$"\"duration\": {duration}"+
"}]", Encoding.UTF8, new MediaTypeHeaderValue("application/json"))
};
this.HttpClient.Send(request);
request.Headers.Add("OpenShockToken", ApiKey);
HttpResponseMessage response = this.HttpClient.Send(request);
Console.WriteLine($"{request.RequestUri} response: {response.StatusCode}");
}
private byte ControlActionToByte(ControlAction action)
@ -44,7 +37,7 @@ public class OpenShock : Shocker
};
}
public OpenShock(string endpoint, string apiKey, string[] shockerIds, ConfiguredInteger intensity, ConfiguredInteger duration) : base(endpoint, apiKey, shockerIds, intensity, duration)
internal OpenShock(string endpoint, string apiKey, string[] shockerIds, ConfiguredInteger intensity, ConfiguredInteger duration) : base(endpoint, apiKey, shockerIds, intensity, duration)
{
}

View File

@ -1,7 +1,10 @@
namespace OpenCS2hock;
using Newtonsoft.Json;
namespace OpenCS2hock;
public struct Settings
{
public string SteamId = "";
public OpenShockSettings OpenShockSettings = new()
{
Endpoint = "https://api.shocklink.net",
@ -11,14 +14,14 @@ public struct Settings
public Range IntensityRange = new ()
{
Min = 0,
Max = 100
Min = 20,
Max = 60
};
public Range DurationRange = new()
{
Min = 1000,
Max = 2000
Max = 1000
};
public Dictionary<string, string> Actions = new()
@ -36,7 +39,12 @@ public struct Settings
}
public static Shocker.ControlAction StringToAction(string str)
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
internal static Shocker.ControlAction StringToAction(string str)
{
return str.ToLower() switch
{

View File

@ -1,23 +1,37 @@
namespace OpenCS2hock;
public abstract class Shocker
internal abstract class Shocker
{
protected readonly HttpClient HttpClient;
protected readonly string ApiKey,Endpoint;
protected readonly string[] ShockerIds;
protected readonly ConfiguredInteger Intensity, Duration;
private readonly string[] _shockerIds;
private readonly ConfiguredInteger _intensity, _duration;
public enum ControlAction { Beep, Vibrate, Shock, Nothing }
internal enum ControlAction { Beep, Vibrate, Shock, Nothing }
public abstract void Control(ControlAction action, string? shockerId = null);
internal void Control(ControlAction action, string? shockerId = null)
{
int intensity = _intensity.GetValue();
int duration = _duration.GetValue();
Console.WriteLine($"{action} {intensity} {duration}");
if (action is ControlAction.Nothing)
return;
if(shockerId is null)
foreach (string shocker in _shockerIds)
ControlInternal(action, shocker, intensity, duration);
else
ControlInternal(action, shockerId, intensity, duration);
}
protected abstract void ControlInternal(ControlAction action, string shockerId, int intensity, int duration);
protected Shocker(string endpoint, string apiKey, string[] shockerIds, ConfiguredInteger intensity, ConfiguredInteger duration)
{
this.Endpoint = endpoint;
this.ApiKey = apiKey;
this.HttpClient = new HttpClient();
this.ShockerIds = shockerIds;
this.Intensity = intensity;
this.Duration = duration;
this._shockerIds = shockerIds;
this._intensity = intensity;
this._duration = duration;
}
}

View File

@ -1,9 +1,9 @@
"OpenCS2hock"
{
"uri" "http://127.0.0.1:3000"
"timeout" "5.0"
"buffer" "0.1"
"throttle" "0.5"
"timeout" "2.0"
"buffer" "0.0"
"throttle" "0.1"
"heartbeat" "60.0"
"output"
{