Skip to content

Commit

Permalink
update JSON serialization to use numeric enums:
Browse files Browse the repository at this point in the history
    Remove JsonStringEnumConverter from enums and global options
    Modify ParametersConverter to convert enums to integers
    Restores compatibility with 0.6.2 JSON format for DSX communication
  • Loading branch information
cosmii02 committed Dec 7, 2024
1 parent a63000c commit c57fdf4
Show file tree
Hide file tree
Showing 5 changed files with 138 additions and 22 deletions.
139 changes: 131 additions & 8 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
Expand All @@ -8,7 +9,7 @@ namespace RacingDSX
{
public class Program
{
public const String VERSION = "0.6.4";
public const String VERSION = "0.6.5";

[STAThread]
static void Main(string[] args)
Expand Down Expand Up @@ -36,6 +37,95 @@ static void Main(string[] args)
}
}

public class ParametersConverter : JsonConverter<object[]>
{
public override object[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartArray)
{
throw new JsonException("Expected start of array");
}

var parameters = new List<object>();
reader.Read(); // Move past StartArray

while (reader.TokenType != JsonTokenType.EndArray)
{
switch (reader.TokenType)
{
case JsonTokenType.Number:
if (reader.TryGetInt32(out int intValue))
parameters.Add(intValue);
else if (reader.TryGetDouble(out double doubleValue))
parameters.Add(doubleValue);
break;
case JsonTokenType.String:
string stringValue = reader.GetString();
// Convert enum strings to their numeric values
if (Enum.TryParse<Trigger>(stringValue, out var trigger))
parameters.Add((int)trigger);
else if (Enum.TryParse<TriggerMode>(stringValue, out var triggerMode))
parameters.Add((int)triggerMode);
else if (Enum.TryParse<CustomTriggerValueMode>(stringValue, out var customTrigger))
parameters.Add((int)customTrigger);
else if (Enum.TryParse<PlayerLEDNewRevision>(stringValue, out var playerLed))
parameters.Add((int)playerLed);
else if (Enum.TryParse<MicLEDMode>(stringValue, out var micLed))
parameters.Add((int)micLed);
else
parameters.Add(stringValue);
break;
case JsonTokenType.True:
case JsonTokenType.False:
parameters.Add(reader.GetBoolean());
break;
case JsonTokenType.Null:
parameters.Add(null);
break;
}
reader.Read();
}

return parameters.ToArray();
}

public override void Write(Utf8JsonWriter writer, object[] value, JsonSerializerOptions options)
{
writer.WriteStartArray();
foreach (var item in value)
{
if (item == null)
{
writer.WriteNullValue();
continue;
}

switch (item)
{
case int intValue:
writer.WriteNumberValue(intValue);
break;
case double doubleValue:
writer.WriteNumberValue(doubleValue);
break;
case string stringValue:
writer.WriteStringValue(stringValue);
break;
case bool boolValue:
writer.WriteBooleanValue(boolValue);
break;
case Enum enumValue:
writer.WriteNumberValue(Convert.ToInt32(enumValue));
break;
default:
writer.WriteNumberValue(Convert.ToInt32(item));
break;
}
}
writer.WriteEndArray();
}
}

public static class Triggers
{
public static IPAddress localhost = new IPAddress(new byte[] { 127, 0, 0, 1 });
Expand All @@ -44,7 +134,10 @@ public static class Triggers
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = false,
Converters = { new JsonStringEnumConverter() }
Converters =
{
new ParametersConverter()
}
};

public static string PacketToJson(Packet packet)
Expand Down Expand Up @@ -73,7 +166,6 @@ public static Packet JsonToPacket(string json)
}
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum TriggerMode
{
Normal = 0,
Expand All @@ -94,10 +186,17 @@ public enum TriggerMode
Galloping = 15,
SemiAutomaticGun = 16,
AutomaticGun = 17,
Machine = 18
Machine = 18,
OFF = 19,
FEEDBACK = 20,
WEAPON = 21,
VIBRATION = 22,
SLOPE_FEEDBACK = 23,
MULTIPLE_POSITION_FEEDBACK = 24,
MULTIPLE_POSITION_VIBRATION = 25,
VIBRATE_TRIGGER_10Hz = 26
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum CustomTriggerValueMode
{
OFF = 0,
Expand All @@ -119,22 +218,40 @@ public enum CustomTriggerValueMode
VibratePulseAB = 16
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Trigger
{
Invalid,
Left,
Right
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum InstructionType
{
Invalid,
TriggerUpdate,
RGBUpdate,
PlayerLED,
TriggerThreshold
PlayerLEDNewRevision,
MicLED,
TriggerThreshold,
ResetToUserSettings,
GetDSXStatus
}

public enum PlayerLEDNewRevision
{
One,
Two,
Three,
Four,
Five
}

public enum MicLEDMode
{
Off,
On,
Pulse
}

public class Instruction
Expand All @@ -149,12 +266,18 @@ public Instruction(InstructionType type)
public InstructionType Type { get; set; }

[JsonPropertyName("parameters")]
[JsonConverter(typeof(ParametersConverter))]
public object[] Parameters { get; set; }
}

public class Packet
{
[JsonPropertyName("instructions")]
public Instruction[] Instructions { get; set; }

public Packet()
{
Instructions = Array.Empty<Instruction>();
}
}
}
15 changes: 4 additions & 11 deletions obj/project.assets.json
Original file line number Diff line number Diff line change
Expand Up @@ -809,8 +809,7 @@
]
},
"packageFolders": {
"C:\\Users\\apple\\.nuget\\packages\\": {},
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages": {}
"C:\\Users\\apple\\.nuget\\packages\\": {}
},
"project": {
"version": "1.0.0",
Expand All @@ -822,19 +821,13 @@
"outputPath": "C:\\Users\\apple\\RiderProjects\\RacingDSX\\obj\\",
"projectStyle": "PackageReference",
"UsingMicrosoftNETSdk": false,
"fallbackFolders": [
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"
],
"configFilePaths": [
"C:\\Users\\apple\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
"C:\\Users\\apple\\AppData\\Roaming\\NuGet\\NuGet.Config"
],
"originalTargetFrameworks": [
"net8.0-windows"
],
"sources": {
"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
Expand All @@ -851,7 +844,7 @@
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "all"
"auditMode": "direct"
}
},
"frameworks": {
Expand Down Expand Up @@ -898,7 +891,7 @@
"privateAssets": "none"
}
},
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\9.0.100/PortableRuntimeIdentifierGraph.json"
"runtimeIdentifierGraphPath": "C:\\Users\\apple\\.dotnet\\sdk\\8.0.404/PortableRuntimeIdentifierGraph.json"
}
},
"runtimes": {
Expand Down
2 changes: 1 addition & 1 deletion obj/project.nuget.cache
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"version": 2,
"dgSpecHash": "tiLd3/+mwxw=",
"dgSpecHash": "hBUUivvPYQA=",
"success": true,
"projectFilePath": "C:\\Users\\apple\\RiderProjects\\RacingDSX\\RacingDSX.csproj",
"expectedPackageFiles": [
Expand Down
2 changes: 1 addition & 1 deletion obj/project.packagespec.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"restore":{"projectUniqueName":"C:\\Users\\apple\\RiderProjects\\RacingDSX\\RacingDSX.csproj","projectName":"RacingDSX","projectPath":"C:\\Users\\apple\\RiderProjects\\RacingDSX\\RacingDSX.csproj","outputPath":"C:\\Users\\apple\\RiderProjects\\RacingDSX\\obj\\","projectStyle":"PackageReference","UsingMicrosoftNETSdk":false,"fallbackFolders":["C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"],"originalTargetFrameworks":["net8.0-windows"],"sources":{"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\":{},"https://api.nuget.org/v3/index.json":{}},"frameworks":{"net8.0-windows7.0":{"targetAlias":"net8.0-windows","projectReferences":{}}},"warningProperties":{"warnAsError":["NU1605"]},"restoreAuditProperties":{"enableAudit":"true","auditLevel":"low","auditMode":"all"}}"frameworks":{"net8.0-windows7.0":{"targetAlias":"net8.0-windows","dependencies":{"CsvHelper":{"target":"Package","version":"[33.0.1, )"},"Microsoft.Extensions.Configuration.Binder":{"target":"Package","version":"[9.0.0, )"},"Microsoft.Extensions.Configuration.EnvironmentVariables":{"target":"Package","version":"[9.0.0, )"},"Microsoft.Extensions.Configuration.Ini":{"target":"Package","version":"[9.0.0, )"},"Newtonsoft.Json":{"target":"Package","version":"[13.0.3, )"}},"imports":["net461","net462","net47","net471","net472","net48","net481"],"assetTargetFallback":true,"warn":true,"frameworkReferences":{"Microsoft.NETCore.App":{"privateAssets":"all"},"Microsoft.WindowsDesktop.App.WindowsForms":{"privateAssets":"none"}},"runtimeIdentifierGraphPath":"C:\\Program Files\\dotnet\\sdk\\9.0.100/PortableRuntimeIdentifierGraph.json"}}"runtimes":{"win-x64":{"#import":[]}}
"restore":{"projectUniqueName":"C:\\Users\\apple\\RiderProjects\\RacingDSX\\RacingDSX.csproj","projectName":"RacingDSX","projectPath":"C:\\Users\\apple\\RiderProjects\\RacingDSX\\RacingDSX.csproj","outputPath":"C:\\Users\\apple\\RiderProjects\\RacingDSX\\obj\\","projectStyle":"PackageReference","UsingMicrosoftNETSdk":false,"originalTargetFrameworks":["net8.0-windows"],"sources":{"https://api.nuget.org/v3/index.json":{}},"frameworks":{"net8.0-windows7.0":{"targetAlias":"net8.0-windows","projectReferences":{}}},"warningProperties":{"warnAsError":["NU1605"]},"restoreAuditProperties":{"enableAudit":"true","auditLevel":"low","auditMode":"direct"}}"frameworks":{"net8.0-windows7.0":{"targetAlias":"net8.0-windows","dependencies":{"CsvHelper":{"target":"Package","version":"[33.0.1, )"},"Microsoft.Extensions.Configuration.Binder":{"target":"Package","version":"[9.0.0, )"},"Microsoft.Extensions.Configuration.EnvironmentVariables":{"target":"Package","version":"[9.0.0, )"},"Microsoft.Extensions.Configuration.Ini":{"target":"Package","version":"[9.0.0, )"},"Newtonsoft.Json":{"target":"Package","version":"[13.0.3, )"}},"imports":["net461","net462","net47","net471","net472","net48","net481"],"assetTargetFallback":true,"warn":true,"frameworkReferences":{"Microsoft.NETCore.App":{"privateAssets":"all"},"Microsoft.WindowsDesktop.App.WindowsForms":{"privateAssets":"none"}},"runtimeIdentifierGraphPath":"C:\\Users\\apple\\.dotnet\\sdk\\8.0.404/PortableRuntimeIdentifierGraph.json"}}"runtimes":{"win-x64":{"#import":[]}}
2 changes: 1 addition & 1 deletion obj/rider.project.restore.info
Original file line number Diff line number Diff line change
@@ -1 +1 @@
17335668337895570
17335781656703585

0 comments on commit c57fdf4

Please sign in to comment.