CShock/CShocker/Shockers/APIS/OpenShockSerial.cs

63 lines
2.4 KiB
C#
Raw Normal View History

2024-01-20 20:02:05 +01:00
using System.Text.RegularExpressions;
using CShocker.Ranges;
2024-01-17 17:59:10 +01:00
using CShocker.Shockers.Abstract;
2024-01-17 04:11:30 +01:00
using Microsoft.Extensions.Logging;
2024-01-17 22:16:40 +01:00
namespace CShocker.Shockers.APIS;
2024-01-17 04:11:30 +01:00
2024-01-17 04:36:38 +01:00
public class OpenShockSerial : SerialShocker
2024-01-17 04:11:30 +01:00
{
2024-01-20 20:02:05 +01:00
public readonly Dictionary<string, ShockerModel> Model;
private const int BaudRate = 115200;
public OpenShockSerial(Dictionary<string, ShockerModel> shockerIds, IntensityRange intensityRange, DurationRange durationRange, SerialPortInfo serialPortI, ILogger? logger = null) : base(shockerIds.Keys.ToList(), intensityRange, durationRange, serialPortI, BaudRate, ShockerApi.OpenShockSerial, logger)
2024-01-17 04:11:30 +01:00
{
2024-01-20 20:02:05 +01:00
this.Model = shockerIds;
2024-01-17 04:11:30 +01:00
}
protected override void ControlInternal(ControlAction action, string shockerId, int intensity, int duration)
{
2024-01-20 20:19:25 +01:00
string json = "rftransmit {" +
2024-01-20 20:02:05 +01:00
$"\"model\":\"{Enum.GetName(Model[shockerId])!.ToLower()}\"," +
$"\"id\":{shockerId}," +
$"\"type\":\"{ControlActionToString(action)}\"," +
$"\"intensity\":{intensity}," +
$"\"durationMs\":{duration}" +
"}";
serialPort.WriteLine(json);
}
public Dictionary<string, ShockerModel> GetShockers()
{
Dictionary<string, ShockerModel> ret = new();
Regex shockerRex = new (@".*FetchDeviceInfo\(\): \[GatewayConnectionManager\] \[[a-z0-9\-]+\] rf=([0-9]{1,5}) model=([0,1])");
this.Logger?.Log(LogLevel.Debug, "Restart");
serialPort.WriteLine("restart");
while (serialPort.ReadLine() is { } line && !line.Contains("Successfully verified auth token"))
{
this.Logger?.Log(LogLevel.Trace, line);
Match match = shockerRex.Match(line);
if (match.Success)
ret.Add(match.Groups[1].Value, Enum.Parse<ShockerModel>(match.Groups[2].Value));
}
this.Logger?.Log(LogLevel.Debug, $"Shockers found: \n\t{string.Join("\n\t", ret)}");
return ret;
}
public enum ShockerModel : byte
{
Caixianlin = 0,
Petrainer = 1
}
private string ControlActionToString(ControlAction action)
{
return action switch
{
ControlAction.Beep => "sound",
ControlAction.Vibrate => "vibrate",
ControlAction.Shock => "shock",
_ => "stop"
};
2024-01-17 04:11:30 +01:00
}
}