HamBook – Rev 46

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

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

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

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

        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();
            }
        }
    }
}