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 TX : Generic.CAT.TX
{
private Regex readRegex;
public override CatLength CatLength => new CatLength { Set = 4, Read = 3, Answer = 4 };
public TX(SerialPortStream serialPort) : base(serialPort)
{
readRegex = new Regex($"^{Name}(?<state>[0-9]){Constants.EOT}$", RegexOptions.Compiled);
}
public override TxState Read()
{
SerialPort.Write($"{Name}{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 (TxState)int.Parse(match.Result("${state}"));
}
public override async Task<TxState> ReadAsync(CancellationToken cancellationToken)
{
var payload = Constants.Encoding.GetBytes($"{Name}{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 (TxState)int.Parse(match.Result("${state}"));
}
public override bool Set(TxState state)
{
var payload = Constants.Encoding.GetBytes($"{Name}{(int)state}{Constants.EOT}");
SerialPort.Write(payload, 0, payload.Length);
return Read() == state;
}
public override async Task<bool> SetAsync(TxState state, CancellationToken cancellationToken)
{
var payload = Constants.Encoding.GetBytes($"{Name}{(int)state}{Constants.EOT}");
await SerialPort.WriteAsync(payload, 0, payload.Length, cancellationToken);
return await ReadAsync(cancellationToken) == state;
}
public override void Write(TxState state)
{
SerialPort.Write($"{Name}{(int)state}{Constants.EOT}");
}
public override async Task WriteAsync(TxState state, CancellationToken cancellationToken)
{
var payload = Constants.Encoding.GetBytes($"{Name}{(int)state}{Constants.EOT}");
await SerialPort.WriteAsync(payload, 0, payload.Length, cancellationToken);
}
}
}