using Microsoft.Extensions.DependencyInjection;
using SlnMesnac.Config;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SlnMesnac.Common
{
///
/// 光源控制类
///
public sealed class LightHelper
{
#region 单例实现
private static readonly LightHelper lazy = new LightHelper();
public static LightHelper Instance
{
get
{
return lazy;
}
}
#endregion
#region 变量定义
private static SerialPort serialPort = new SerialPort();
#endregion
private DebugConfig config = DebugConfig.Instance;
//初始化串口并启动接收数据
public void InstanceSerialPort()
{
try
{
serialPort.PortName = config.LightPort;// portName;
serialPort.BaudRate = 115200;
//奇偶校验
serialPort.Parity = Parity.None;
//停止位
serialPort.StopBits = StopBits.One;
//数据位
serialPort.DataBits = 0x8;
//忽略null字节
serialPort.DiscardNull = true;
//接收事件
serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
//开启串口
serialPort.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
///
/// 接收数据
///
///
///
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string result = "";
int bytesToRead = serialPort.BytesToRead;
byte[] buf = new byte[bytesToRead];
serialPort.Read(buf, 0x0, bytesToRead);
for (int i = 0x0; i < buf.Length; i++)
{
int num = (int)buf[i];
result =result+num.ToString("X2");
}
Console.WriteLine(result);
}
///
/// 发送数据方法
/// OK-校验成功关闭灯光,NG-校验失败闪烁红灯
///
///
public void SendData(string data)
{
try
{
if (serialPort.IsOpen)
{
if (data == "OPEN")
{
// 第1通道亮度200
serialPort.WriteLine("$310C86E");
// 第2通道亮度200
serialPort.WriteLine("$320C86E");
}
else if (data == "CLOSE")
{
// 第2通道亮度0
serialPort.WriteLine("$3100004");
// 第2通道亮度0
serialPort.WriteLine("$3200005");
}
}
else
{
Console.WriteLine("串口未打开,请先初始化串口并打开连接。");
}
}
catch (Exception ex)
{
Console.WriteLine($"发送数据时发生错误:{ex.Message}");
}
}
}
}