HamBook – Rev 1

Subversion Repositories:
Rev:
using HamBook.Properties;
using Org.BouncyCastle.Utilities;
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 SerialPort _serialPort;
        private string _radio;

        private readonly ConcurrentDictionary<string, Cat> _catCommands;

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

        public CatAssemblies(SerialPort 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(SerialPort) })
                                            .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 async Task CatSet<T>(string command, object[] param, CancellationToken cancellationToken)
        {
            _serialPort.Open();
            try
            {
                if (_catCommands.TryGetValue(command, out var catCommand))
                {
                    var methodInfo = catCommand.GetType().GetMethod("Set");
                    if (methodInfo != null)
                    {
                        if (methodInfo.GetCustomAttribute<AsyncStateMachineAttribute>() != null)
                        {
                            await (Task)methodInfo.Invoke(catCommand, param);
                        }
                    }
                }
            }
            finally
            {
                _serialPort.Close();
            }
        }

        public void CatSet<T>(string command, object[] param)
        {
            _serialPort.Open();
            try
            {
                if (_catCommands.TryGetValue(command, out var catCommand))
                {
                    var methodInfo = catCommand.GetType().GetMethod("Set");
                    if (methodInfo != null)
                    {
                        methodInfo.Invoke(catCommand, param);
                    }
                }
            }
            finally
            {
                _serialPort.Close();
            }
        }

        public T CatRead<T>(string command, object[] param)
        {
            _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);
                    }
                }
            }
            finally
            {
                _serialPort.Close();
            }

            return default;
        }

        public async Task<T> CatRead<T>(string command, object[] param, CancellationToken cancellationToken)
        {
            _serialPort.Open();
            try
            {
                if (_catCommands.TryGetValue(command, out var catCommand))
                {
                    var methodInfo = catCommand.GetType().GetMethod("Read");
                    if (methodInfo != null)
                    {
                        if(methodInfo.GetCustomAttribute<AsyncStateMachineAttribute>() != null)
                        {
                            return await (Task<T>)methodInfo.Invoke(catCommand, param);
                        }
                    }
                }
            }
            finally
            {
                _serialPort.Close();
            }

            return default;
        }
    }
}