using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Diagnostics;

namespace WiPoMServer
{
    /// <summary>
    /// Interface for communicating over serial to zigbee.
    /// But only value will be sent (range 0-255)
    /// Actual Power value will be generated from sent value --> fake!
    /// </summary>
    public class DimmerInterface: IDisposable
    {
        SerialPort serial;

        public DimmerInterface()
        {
            this.serial = new SerialPort(Properties.Settings.Default.ComPort,115200, Parity.None, 8, StopBits.One);
            //this.serial.WriteBufferSize = 1;
            serial.Encoding = Encoding.ASCII;
            serial.Open();
        }

        public void WriteValue(int no)
        {
            //Debug.WriteLine("Write value:\t" + (char)((byte)no));
            byte[] data = new byte[1]; // Encoding.ASCII.GetBytes(chars);
            data[0] = (byte)no;
            serial.BaseStream.Write(data, 0, 1);
            //Debug.WriteLine("Data:\t" + data);
            //this.serial.Write(data, 0, data.Length);
        }

        public void TestChars()
        {
            for (int i = 0; i < 256; i++)
            {
                Debug.WriteLine(i + "\t" + (char)((byte)i));
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            try
            {
                if (serial != null)
                    if (this.serial.IsOpen)
                        this.serial.Close();
            }
            catch { }
        }

        #endregion
    }
}
