using System;
|
using System.Collections.Generic;
|
using System.IO.Ports;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
using Quartz;
|
using WIDESEAWCS_QuartzJob;
|
|
namespace WIDESEAWCS_Tasks
|
{
|
[DisallowConcurrentExecution]
|
public class SerialPortJob : JobBase, IJob
|
{
|
public enum CommandType
|
{
|
None = 0,
|
Get = 1,
|
Set = 2,
|
}
|
private static SerialPort serialPort;
|
private static CommandType commandType = CommandType.None;
|
private string commandGet = "824070241JNT\r";//读值
|
private string commandSet = "824070241JNT,0005000,+0001000[+TOL],-0001000[-TOL]\r";//设值
|
private string setOK = "ParseOK";
|
private string getOK = "82407024103";
|
private string getError = "82407024104";
|
public Task Execute(IJobExecutionContext context)
|
{
|
try
|
{
|
if (serialPort == null) { serialPort = new SerialPort("COM3"); serialPort.DataReceived += SerialPort_DataReceived; }
|
if (!serialPort.IsOpen)
|
{
|
serialPort.Open();
|
|
|
|
serialPort.Write(commandSet);//打开串口时先设值
|
commandType = CommandType.Set;
|
}
|
switch (commandType)
|
{
|
case CommandType.Get:
|
serialPort.Write(commandGet);
|
break;
|
case CommandType.Set:
|
serialPort.Write(commandSet);
|
break;
|
}
|
}
|
catch (Exception ex)
|
{
|
throw new Exception(ex.Message);
|
}
|
return Task.CompletedTask;
|
}
|
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
|
{
|
byte[] buffers = new byte[1024];
|
while (serialPort.BytesToRead > 0)
|
{
|
serialPort.Read(buffers, 0, serialPort.BytesToRead > buffers.Length ? buffers.Length : serialPort.BytesToRead);
|
string data = Encoding.Default.GetString(buffers);
|
if (data.Contains(setOK) && commandType == CommandType.Set)
|
{
|
commandType = CommandType.Get;
|
}
|
else if (data.Contains(getOK) && commandType == CommandType.Get)
|
{
|
commandType = CommandType.Set;
|
|
|
}
|
else if (data.Contains(getError) && commandType == CommandType.Get)
|
{
|
commandType = CommandType.Set;
|
|
|
}
|
}
|
}
|
}
|
}
|