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