HamBook – Rev 46
?pathlinks?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HamBook.Radios.Generic;
using static HamBook.Radios.Yaesu.FT_891.Constants;
using RJCP.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;
namespace HamBook.Radios.Yaesu.FT_891.CAT
{
[Radio("Yaesu FT-891")]
public class PA : Generic.CAT.PA
{
private Regex readRegex;
public override CatLength CatLength => new CatLength { Set = 5, Read = 4, Answer = 5 };
public PA(SerialPortStream serialPort) : base(serialPort)
{
readRegex = new Regex($"^{Name}0(?<state>[01]){Constants.EOT}$", RegexOptions.Compiled);
}
public override IpoState Read()
{
SerialPort.Write($"{Name}0{Constants.EOT}");
var buffer = new byte[CatLength.Answer];
if (SerialPort.Read(buffer, 0, CatLength.Answer) != CatLength.Answer)
{
throw new UnexpectedRadioResponseException(Name, buffer);
}
var answer = Constants.Encoding.GetString(buffer);
var match = readRegex.Match(answer);
if (!match.Success)
{
throw new UnmatchedRadioResponseException(Name, answer);
}
return (IpoState)int.Parse(match.Result("${state}"));
}
public override async Task<IpoState> ReadAsync(CancellationToken cancellationToken)
{
var payload = Constants.Encoding.GetBytes($"{Name}0{Constants.EOT}");
await SerialPort.WriteAsync(payload, 0, payload.Length, cancellationToken);
var buffer = new byte[CatLength.Answer];
if (await SerialPort.ReadAsync(buffer, 0, CatLength.Answer, cancellationToken) != CatLength.Answer)
{
throw new UnexpectedRadioResponseException(Name, buffer);
}
var answer = Constants.Encoding.GetString(buffer);
var match = readRegex.Match(answer);
if (!match.Success)
{
throw new UnmatchedRadioResponseException(Name, answer);
}
return (IpoState)int.Parse(match.Result("${state}"));
}
public override bool Set(IpoState ipoState)
{
var payload = Constants.Encoding.GetBytes($"{Name}0{(int)ipoState}{Constants.EOT}");
SerialPort.Write(payload, 0, payload.Length);
return Read() == ipoState;
}
public override async Task<bool> SetAsync(IpoState ipoState, CancellationToken cancellationToken)
{
var payload = Constants.Encoding.GetBytes($"{Name}0{(int)ipoState}{Constants.EOT}");
await SerialPort.WriteAsync(payload, 0, payload.Length, cancellationToken);
var result = await ReadAsync(cancellationToken);
return result == ipoState;
}
public override void Write(IpoState ipoState)
{
SerialPort.Write($"{Name}0{(int)ipoState}{Constants.EOT}");
}
public override async Task WriteAsync(IpoState ipoState, CancellationToken cancellationToken)
{
var payload = Constants.Encoding.GetBytes($"{Name}0{(int)ipoState}{Constants.EOT}");
await SerialPort.WriteAsync(payload, 0, payload.Length, cancellationToken);
}
}
}