HamBook – Rev 38

Subversion Repositories:
Rev:
using HamBook.Properties;
using Org.BouncyCastle.Utilities;
using RJCP.IO.Ports;
using Serilog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;

namespace HamBook.Radios
{
    public class CatAssemblies : IDisposable
    {
        public int Count => _count;

        private int _count;
        private SerialPortStream _serialPort;
        private string _radio;

        private ConcurrentDictionary<string, Cat> _catCommands;
        private SemaphoreSlim _semaphoreSlim;

        private CatAssemblies()
        {
            _catCommands = new ConcurrentDictionary<string, Cat>();
            _semaphoreSlim = new SemaphoreSlim(1, 1);
        }

        public CatAssemblies(SerialPortStream serialPort, string radio) : this()
        {
            _serialPort = serialPort;
            _radio = radio;

            Load(_radio);
        }
        public void Dispose()
        {
            Unload();
        }

        private void Load(string radio)
        {
            Interlocked.Exchange(ref _count, 0);

            foreach (var type in Assembly.GetExecutingAssembly()
                                         .GetTypes()
                                         .Where(type => type.IsSubclassOf(typeof(Cat)))
                                         .Where(type => type.GetCustomAttribute<RadioAttribute>() !=null && type.GetCustomAttribute<RadioAttribute>().Radio == radio))
            {
                try
                {
                    var catCommand = (Cat)type
                                            .GetConstructor(new[] { typeof(SerialPortStream) })
                                            .Invoke(new [] { _serialPort });

                    if (catCommand == null)
                    {
                        throw new ArgumentException(Resources.Could_not_create_assembly);
                    }

                    if (!_catCommands.TryAdd(catCommand.Name, catCommand))
                    {
                        Log.Warning(Resources.Unable_to_register_assembly, catCommand.Name);

                        catCommand.Dispose();

                        continue;
                    }

                    //BindEventHandlers(command);

                    Interlocked.Increment(ref _count);
                }
                catch (Exception exception)
                {
                    Log.Error(exception, Resources.Could_not_instantiate_assembly, type);
                }
            }

            Log.Information(Resources.Registering_commands, Count);
        }

        private void Unload()
        {
            // Dispose all command assemblies.
            var list = new List<Cat>(_catCommands.Values);

            for (var i = 0; i < list.Count; ++i)
            {
                try
                {
                    //UnbindEventHandlers(list[i]);

                    if (list[i] != null)
                    {
                        Log.Debug(Resources.Disposing_assembly, list[i].GetType().Name);

                        list[i]
                            .Dispose();

                        list[i] = null;
                    }
                }
                catch (NullReferenceException)
                {
                    // Already removed.
                }
                catch (ObjectDisposedException)
                {
                    list[i] = null;
                }
                catch (Exception exception)
                {
                    Log.Error(exception, Resources.Error_encountered_while_disposing_object);
                }
            }

            _catCommands.Clear();
        }

        public T CatParse<T>(string command, object[] param)
        {
            if (_catCommands.TryGetValue(command, out var catCommand))
            {
                var methodInfo = catCommand.GetType().GetMethod("Parse");
                if (methodInfo != null)
                {
                    return (T)methodInfo.Invoke(catCommand, param);
                }

                throw new CatCommandException(Resources.CAT_command_method_not_found, command, "Parse");
            }

            throw new CatCommandException(Resources.CAT_command_not_found, command);
        }

        public T CatGetDefault<T>(string command, object[] param)
        {
            _semaphoreSlim.Wait();

            try
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }

                try
                {
                    if (_catCommands.TryGetValue(command, out var catCommand))
                    {
                        var methodInfo = catCommand.GetType().GetMethod("GetDefault");
                        if (methodInfo != null)
                        {
                            return (T)methodInfo.Invoke(catCommand, param);
                        }
                    }
                }
                finally
                {
                    if (_serialPort.IsOpen)
                    {
                        _serialPort.Flush();
                        _serialPort.Close();
                    }
                }
            }
            finally
            {
                _semaphoreSlim.Release();
            }

            return default;
        }

        public void CatSet<T>(string command, object[] param)
        {
            _semaphoreSlim.Wait();

            try
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }

                try
                {
                    if (_catCommands.TryGetValue(command, out var catCommand))
                    {
                        var methodInfo = catCommand.GetType().GetMethod("Set");
                        if (methodInfo != null)
                        {
                            methodInfo.Invoke(catCommand, param);

                            return;
                        }

                        throw new CatCommandException(Resources.CAT_command_method_not_found, command, "Set");
                    }

                    throw new CatCommandException(Resources.CAT_command_not_found, command);
                }
                finally
                {
                    if (_serialPort.IsOpen)
                    {
                        _serialPort.Flush();
                        _serialPort.Close();
                    }
                }
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }

        public async Task<U> CatSetAsync<T, U>(string command, object[] param, CancellationToken cancellationToken)
        {
            await _semaphoreSlim.WaitAsync(cancellationToken);

            try
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }

                try
                {
                    if (_catCommands.TryGetValue(command, out var catCommand))
                    {
                        var methodInfo = catCommand.GetType().GetMethod("SetAsync");
                        if (methodInfo != null)
                        {
                            if (methodInfo.GetCustomAttribute<AsyncStateMachineAttribute>() != null)
                            {
                                var parameters = new List<object>();
                                parameters.AddRange(param);
                                parameters.Add(cancellationToken);

                                var result = await (Task<U>)methodInfo.Invoke(catCommand, parameters.ToArray());

                                return result;
                            }
                        }
                        throw new CatCommandException(Resources.CAT_command_method_not_found, command, "SetAsync");
                    }

                    throw new CatCommandException(Resources.CAT_command_not_found, command);
                }
                finally
                {
                    if (_serialPort.IsOpen)
                    {
                        await _serialPort.FlushAsync(cancellationToken);
                        _serialPort.Close();
                    }
                }
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }

        public void CatWrite<T>(string command, object[] param)
        {
            _semaphoreSlim.Wait();

            try
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }

                try
                {
                    if (_catCommands.TryGetValue(command, out var catCommand))
                    {
                        var methodInfo = catCommand.GetType().GetMethod("Write");
                        if (methodInfo != null)
                        {
                            methodInfo.Invoke(catCommand, param);

                            return;
                        }

                        throw new CatCommandException(Resources.CAT_command_method_not_found, command, "Write");
                    }

                    throw new CatCommandException(Resources.CAT_command_not_found, command);
                }
                finally
                {
                    if (_serialPort.IsOpen)
                    {
                        _serialPort.Flush();
                    }
                }
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }

        public async Task CatWriteAsync<T>(string command, object[] param, CancellationToken cancellationToken)
        {
            await _semaphoreSlim.WaitAsync(cancellationToken);

            try
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }

                try
                {
                    if (_catCommands.TryGetValue(command, out var catCommand))
                    {
                        var methodInfo = catCommand.GetType().GetMethod("WriteAsync");
                        if (methodInfo != null)
                        {
                            if (methodInfo.GetCustomAttribute<AsyncStateMachineAttribute>() != null)
                            {
                                var parameters = new List<object>();
                                parameters.AddRange(param);
                                parameters.Add(cancellationToken);

                                await (Task)methodInfo.Invoke(catCommand, parameters.ToArray());

                                return;
                            }
                        }

                        throw new CatCommandException(Resources.CAT_command_method_not_found, command, "WriteAsync");
                    }

                    throw new CatCommandException(Resources.CAT_command_not_found, command);
                }
                finally
                {
                    if (_serialPort.IsOpen)
                    {
                        await _serialPort.FlushAsync(cancellationToken);
                    }
                }
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }

        public async Task CatWriteAsync(string command, object[] param, CancellationToken cancellationToken)
        {
            await _semaphoreSlim.WaitAsync(cancellationToken);

            try
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }

                try
                {
                    if (_catCommands.TryGetValue(command, out var catCommand))
                    {
                        var methodInfo = catCommand.GetType().GetMethod("WriteAsync");
                        if (methodInfo != null)
                        {
                            if (methodInfo.GetCustomAttribute<AsyncStateMachineAttribute>() != null)
                            {
                                var parameters = new List<object>();
                                parameters.AddRange(param);
                                parameters.Add(cancellationToken);

                                await (Task)methodInfo.Invoke(catCommand, parameters.ToArray());

                                return;
                            }
                        }

                        throw new CatCommandException(Resources.CAT_command_method_not_found, command, "WriteAsync");
                    }

                    throw new CatCommandException(Resources.CAT_command_not_found, command);
                }
                finally
                {
                    if (_serialPort.IsOpen)
                    {
                        await _serialPort.FlushAsync(cancellationToken);
                    }
                }
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }

        public T CatRead<T>(string command, object[] param)
        {
            _semaphoreSlim.Wait();

            try
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }

                try
                {
                    if (_catCommands.TryGetValue(command, out var catCommand))
                    {
                        var methodInfo = catCommand.GetType().GetMethod("Read");
                        if (methodInfo != null)
                        {
                            return (T)methodInfo.Invoke(catCommand, param);
                        }

                        throw new CatCommandException(Resources.CAT_command_method_not_found, command, "Read");
                    }

                    throw new CatCommandException(Resources.CAT_command_not_found, command);
                }
                finally
                {
                    if (_serialPort.IsOpen)
                    {
                        _serialPort.Flush();
                        _serialPort.Close();
                    }
                }
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }

        public async Task<T> CatReadAsync<T>(string command, object[] param, CancellationToken cancellationToken)
        {
            await _semaphoreSlim.WaitAsync(cancellationToken);

            try
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }

                try
                {
                    if (_catCommands.TryGetValue(command, out var catCommand))
                    {
                        var methodInfo = catCommand.GetType().GetMethod("ReadAsync");
                        if (methodInfo != null)
                        {
                            if (methodInfo.GetCustomAttribute<AsyncStateMachineAttribute>() != null)
                            {
                                var parameters = new List<object>();
                                parameters.AddRange(param);
                                parameters.Add(cancellationToken);

                                var result = await (Task<T>)methodInfo.Invoke(catCommand, parameters.ToArray());

                                return result;
                            }
                        }

                        throw new CatCommandException(Resources.CAT_command_method_not_found, command, "ReadAsync");
                    }

                    throw new CatCommandException(Resources.CAT_command_not_found, command);
                }
                finally
                {
                    if (_serialPort.IsOpen)
                    {
                        await _serialPort.FlushAsync(cancellationToken);
                        _serialPort.Close();
                    }
                }
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }
    }
}