using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using static ControllerDllCSharp.ClassLibControllerDll;
namespace AssistClient.Device
{
public class LightDev : IDisposable
{
private long portHandle;
///
/// 光源亮度值
///
public int DigitalValue { get; private set; }
public Action WarningEvent;
///
/// 光源亮度值<通道号,亮度值0-255>
///
public Action DigitalEvent;
///
/// 是否打开设备成功
///
public bool IsInit { get; private set; } = false;
//private System.Timers.Timer timer = new System.Timers.Timer();
public LightDev()
{
}
public bool start(int comNum)
{
try
{
int result = CreateSerialPort(comNum, ref portHandle); //创建串口
if (result != SUCCESS)
throw new Exception($"打开光源设备(COM{comNum})失败: {result}");
IsInit = true;
//timer.Elapsed += Timer_Elapsed;
//timer.Interval = 100;
//timer.Enabled = true;
return true;
}
catch (Exception ex)
{
WarningEvent?.Invoke(WarningEnum.High, ex.Message);
return false;
}
}
public void stop()
{
if (!IsInit) return;
try
{
IsInit = false;
//timer.Elapsed -= Timer_Elapsed;
//timer.Stop();
int result = ReleaseSerialPort(portHandle); //断开串口
}
catch { }
}
public int getDigitalValue(int channelIndex)
{
if (!IsInit) return -1;
int value = 0;
if (GetDigitalValue(ref value, channelIndex, portHandle) != SUCCESS)
return -1;
DigitalEvent?.Invoke(channelIndex, value);
return value;
}
///
/// 设置亮度值
///
/// 通道
/// 0-255
///
public bool setDigitalValue(int channelIndex, int value)
{
if (!IsInit) return false;
Task.Factory.StartNew(() => {
if (SetDigitalValue(channelIndex, value, portHandle) != SUCCESS)
return;// false;
});
return true;
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (!IsInit) return;
}
public void Dispose()
{
stop();
}
}
}