HamBook – Rev 46

Subversion Repositories:
Rev:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static HamBook.Radios.Yaesu.FT_891.Constants;
using RJCP.IO.Ports;
using System.Text.RegularExpressions;
using HamBook.Radios.Generic;

namespace HamBook.Radios.Yaesu.FT_891.CAT
{
    [Radio("Yaesu FT-891")]
    public class BY : Generic.CAT.BY
    {
        private readonly Regex readRegex;

        public override CatLength CatLength => new CatLength { Read = 3, Answer = 5 };

        public BY(SerialPortStream serialPort) : base(serialPort)
        {
            readRegex = new Regex($"^{Name}(?<state>[01])0{Constants.EOT}$", RegexOptions.Compiled);
        }

        public override BusyState Parse(string input)
        {
            var match = readRegex.Match(input);
            if(!match.Success)
            {
                throw new UnmatchedRadioResponseException(Name, input);
            }

            return (BusyState)int.Parse(match.Result("${state}"));
        }

        public override BusyState 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 (BusyState)int.Parse(match.Result("${state}"));
        }
    }
}