Source

TrafficLight / src / Core / Adapters / BusyLightAdapter.cs

Full commit
using System;
using BusyLightHIDCommunications;
using RossCode.TrafficLight.Core.Utilities;

namespace RossCode.TrafficLight.Core.Adapters
{
    public interface IBusylightAdapter : IDisposable
    {
        void TurnGreen();
        void TurnRed();
        void TurnYellow();
        void TurnOff();
    }

    public class BusylightAdapter : IBusylightAdapter
    {
        private UsbDevice busylight;
        private bool isConnected;
        private LinkLampConfiguration.Color currentColor;
        private ITimer timer;

        private bool Connect()
        {
            busylight = new UsbDevice(1240, 63560);
            busylight.FindTargetDevice();
            isConnected = true;

            StartTimer(25);

            return busylight.IsDeviceAttached;
        }

        private void StartTimer(int intervalInSeconds)
        {
            timer = new Timer();
            timer.IntervalInSeconds = intervalInSeconds;
            timer.TimerElapsed += (sender, args) => ChangeColor();
            timer.Start();
        }

        private void ChangeColor()
        {
            if (!isConnected) { if (!Connect()) return; }
            if (currentColor != null)
            {
                busylight.Light(currentColor);
            }
        }

        public void TurnOff()
        {
            if (!isConnected) { if (!Connect()) return; }
            currentColor = new LinkLampConfiguration.Color
                {
                    Red = 0, 
                    Blue = 0, 
                    Green = 0
                };
            ChangeColor();
        }

        public void TurnGreen()
        {
            if (!isConnected) { if (!Connect()) return; }
            currentColor = new LinkLampConfiguration.Color
                {
                    Red = 0, 
                    Blue = 0, 
                    Green = 255
                };
            ChangeColor();
        }

        public void TurnYellow()
        {
            if (!isConnected) { if (!Connect()) return; }
            currentColor = new LinkLampConfiguration.Color
                {
                    Red = 255, 
                    Blue = 0, 
                    Green = 255
                };
            busylight.Light(currentColor);
        }

        public void TurnRed()
        {
            if (!isConnected) { if (!Connect()) return; }
            currentColor = new LinkLampConfiguration.Color
                {
                    Red = 255, 
                    Blue = 0, 
                    Green = 0
                };
            ChangeColor();
        }

        public void Dispose()
        {
            timer.Stop();
            timer = null;

            if (isConnected)
            {
                TurnOff();
                busylight = null;
            }
            isConnected = false;
        }
    }
}