CShock/CShocker/Devices/Additional/DeviceJsonConverter.cs

61 lines
2.3 KiB
C#
Raw Normal View History

using CShocker.Devices.Abstract;
using CShocker.Ranges;
2024-01-17 22:16:40 +01:00
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CShocker.Devices.Additional;
2024-01-17 22:16:40 +01:00
public class DeviceJsonConverter : JsonConverter
2024-01-17 22:16:40 +01:00
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Device));
2024-01-17 22:16:40 +01:00
}
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
DeviceApi? apiType = (DeviceApi?)jo.SelectToken("ApiType")?.Value<byte>();
2024-01-17 22:16:40 +01:00
switch (apiType)
{
case DeviceApi.OpenShockHttp:
2024-01-17 22:16:40 +01:00
return new OpenShockHttp(
2024-01-17 22:49:46 +01:00
jo.SelectToken("IntensityRange")!.ToObject<IntensityRange>()!,
jo.SelectToken("DurationRange")!.ToObject<DurationRange>()!,
jo.SelectToken("ApiKey")!.Value<string>()!,
jo.SelectToken("Endpoint")!.Value<string>()!
2024-01-17 22:16:40 +01:00
);
case DeviceApi.OpenShockSerial:
2024-01-20 20:27:50 +01:00
return new OpenShockSerial(
jo.SelectToken("IntensityRange")!.ToObject<IntensityRange>()!,
jo.SelectToken("DurationRange")!.ToObject<DurationRange>()!,
jo.SelectToken("SerialPortI")!.ToObject<SerialPortInfo>()!,
jo.SelectToken("ApiKey")!.Value<string>()!,
jo.SelectToken("Endpoint")!.Value<string>()!
2024-01-20 20:27:50 +01:00
);
case DeviceApi.PiShockHttp:
return new PiShockHttp(
jo.SelectToken("IntensityRange")!.ToObject<IntensityRange>()!,
jo.SelectToken("DurationRange")!.ToObject<DurationRange>()!,
jo.SelectToken("ApiKey")!.Value<string>()!,
jo.SelectToken("Username")!.Value<string>()!,
jo.SelectToken("Endpoint")!.Value<string>()!
);
case DeviceApi.PiShockSerial:
2024-01-17 22:16:40 +01:00
throw new NotImplementedException();
default:
throw new Exception();
}
}
public override bool CanWrite => false;
/// <summary>
/// Don't call this
/// </summary>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new Exception("Dont call this");
}
}