HamBook – Rev 54

Subversion Repositories:
Rev:
using System;
using System.Text.RegularExpressions;
using HamBook.Radios.Generic;
using RJCP.IO.Ports;

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

        public Ri(SerialPortStream serialPort) : base(serialPort)
        {
            _readRegex = new Regex($"^{Name}(?<type>[03AB]{{1}})(?<state>[01]{{1}}){Constants.Eot}$",
                RegexOptions.Compiled);
        }

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

        public override bool Read(RadioInformationType type)
        {
            SerialPort.Write($"{Name}{P1(type)}{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);

            var information = P1(char.Parse(match.Result("${type}")));

            if (information != type) throw new ArgumentException();

            var state = int.Parse(match.Result("${state}"));
            return state == 1;
        }

        private static RadioInformationType P1(char type)
        {
            switch (type)
            {
                case '0':
                    return RadioInformationType.HI_SWR;
                case '3':
                    return RadioInformationType.REC;
                case '4':
                    return RadioInformationType.PLAY;
                case 'A':
                    return RadioInformationType.TX_LED;
                case 'B':
                    return RadioInformationType.RX_LED;
                default:
                    throw new ArgumentException();
            }
        }

        private static char P1(RadioInformationType type)
        {
            switch (type)
            {
                case RadioInformationType.HI_SWR:
                    return '0';
                case RadioInformationType.REC:
                    return '3';
                case RadioInformationType.PLAY:
                    return '4';
                case RadioInformationType.TX_LED:
                    return 'A';
                case RadioInformationType.RX_LED:
                    return 'B';
                default:
                    throw new ArgumentException();
            }
        }
    }
}

Generated by GNU Enscript 1.6.5.90.