You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

682 lines
38 KiB

using Newtonsoft.Json;
using ScottPlot.Plottables;
using SunlightCentralizedControlManagement_SCCM_.View;
using SunlightCentralizedControlManagement_SCCM_.ViewModel;
using SunlightCentralizedControlManagement_SCCM_.WindowsView;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using TouchSocket.Core;
using TouchSocket.SerialPorts;
using TouchSocket.Sockets;
using static OpenTK.Graphics.OpenGL.GL;
using static SkiaSharp.HarfBuzz.SKShaper;
using static SunlightCentralizedControlManagement_SCCM_.UserClass.SqliteHelper;
using static SunlightCentralizedControlManagement_SCCM_.ViewModel.MainWindowViewModel;
using static System.Net.Mime.MediaTypeNames;
namespace SunlightCentralizedControlManagement_SCCM_.UserClass
{
public class AsyncSerialPortClient
{
public static string ClipBetween(string source, char startChar, char endChar, bool includeBounds = false)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
int startIndex = source.IndexOf(startChar);
if (startIndex == -1) return string.Empty;
int endIndex = source.IndexOf(endChar, startIndex + 1);
if (endIndex == -1) return string.Empty;
if (includeBounds)
{
return source.Substring(startIndex, endIndex - startIndex + 1);
}
else
{
int contentStart = startIndex + 1;
int contentLength = endIndex - startIndex - 1;
return contentLength > 0 ? source.Substring(contentStart, contentLength) : string.Empty;
}
}//获取字符串指定字符的范围的值
public static string PortCOM1 { get; set; }
public static string PortCOM2 { get; set; }
public static string PortCOM3 { get; set; }
public static string PortCOM4 { get; set; }
public static async Task PortClient(SerialPortClient portclient, string com, int BAUD)
{
//var client = new SerialPortClient();
portclient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到端口
portclient.Connected = (client, e) => { return EasyTask.CompletedTask; };//成功连接到端口
portclient.Closing = (client, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
portclient.Closed = (client, e) => { return EasyTask.CompletedTask; };//从端口断开连接,当连接不成功时不会触发。
portclient.Received = (client, e) =>
{
_responseEvent.Set();
string[] sArray = Regex.Split(e.ByteBlock.Span.ToString(Encoding.UTF8),
@"\n", RegexOptions.IgnoreCase);
for (int i = 0; i < sArray.Length; i++)
{
if (sArray[i].Length>5)
{
string SYSAPI = sArray[i].Substring(0, 5);
string Station = ClipBetween(sArray[i], '[', ']');
string DAT = sArray[i].Substring(sArray[i].IndexOf("]") + 1);
if (SYSAPI == "SC800")
{
try
{
Dictionary<string, object> _new = new Dictionary<string, object>();//缓存函数
_new = JsonConvert.DeserializeObject<Dictionary<string, object>>(DAT);//反序列化
lock (MainWindowViewModel.Machines.Rows.SyncRoot)
{
DataRow drEmployee = MainWindowViewModel.Machines.Select("Station='" + Station + "' AND Serial = 'PORT1'").First();
drEmployee.BeginEdit();
drEmployee["State"] = "802";
drEmployee.EndEdit();
drEmployee.AcceptChanges();
}
}
catch (Exception ex)
{
LogGing.ERRDATA(ex); MainWindowViewModel.ERR_c++;
}
}
else if (SYSAPI == "SC810")
{
try
{
Dictionary<string, object> _dat;
_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(DAT);
MainWindowViewModel.SQLiteHelpers.Update("WorkOrder", new Dictionary<string, object> { { "State", 111 } },
"WorkOrder ='" + _dat.GetValue("WorkOrder") + "' AND ReDye ='" + _dat.GetValue("ReDye") + "'", null);
}
catch (Exception ex)
{
LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++;
}
}//回复的工单记录状态后就位111
else if (SYSAPI == "SC811")
{
try
{
Dictionary<string, object> _dat;
_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(DAT);
MainWindowViewModel.SQLiteHelpers.Update("WorkorderSteps", new Dictionary<string, object> { { "Mode", 1 } },
"WorkOrder ='" + _dat.GetValue("Work") + "' AND ReDye ='" + _dat.GetValue("ReDye") + "' AND Step ='" +
_dat.GetValue("Step") + "'", null);
int x = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("select * from WorkorderSteps where WorkOrder='"+
_dat.GetValue("Order") + "' AND ReDye ='" + _dat.GetValue("ReDye") + "' AND Mode <> '1'", null).Tables[0].Rows.Count;
if (x == 0)
{
MainWindowViewModel.SQLiteHelpers.Update("WorkOrder", new Dictionary<string, object> { { "State", 113 } },
"WorkOrder ='" + _dat.GetValue("Order") + "' AND ReDye ='" + _dat.GetValue("ReDye") + "'", null);
}
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//回复的工单明细状态后就位113
else if (SYSAPI == "SC812")
{
try
{
Dictionary<string, object> _dat;
_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(DAT);
MainWindowViewModel.SQLiteHelpers.Update("WorkOrder", new Dictionary<string, object> { { "State", 101 } },
"WorkOrder ='" + _dat.GetValue("WorkOrder") + "' AND ReDye ='" + _dat.GetValue("ReDye") + "'", null);
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//回复的工单设置状态后就位101
else if (SYSAPI == "SC827")
{
try
{
Dictionary<string, object> _dat;
_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(DAT);
DataTable dataTable = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("select * from Dyelot where WorkOrder='" +
_dat.GetValue("WorkOrder") + "' AND ReDye ='" + _dat.GetValue("ReDye") + "' AND Step = '"+ _dat.GetValue("Step") + "'", null).Tables[0];
foreach (DataRow sourceRow in dataTable.Rows)
{
lock (MainWindowViewModel.Dyelot_CALL.Rows.SyncRoot)
{
// 创建新行(基于目标表结构)
DataRow newRow = MainWindowViewModel.Dyelot_CALL.NewRow();
// 复制源表中存在的列数据
foreach (DataColumn column in dataTable.Columns)
{
if (MainWindowViewModel.Dyelot_CALL.Columns.Contains(column.ColumnName))
{
newRow[column.ColumnName] = sourceRow[column.ColumnName];
}
}
MainWindowViewModel.Dyelot_CALL.Rows.Add(newRow);
Dictionary<string, object> Product_ = new Dictionary<string, object>();//缓存函数
Product_.Add("State", 202);
Product_.Add("Dyelot", newRow.Field<string>("Dyelot"));
Product_.Add("Step", newRow.Field<int>("Step"));
newRow.BeginEdit();
newRow["State"] = 202;
newRow.EndEdit();
MainWindowViewModel.SQLiteHelpers.InsertData("DyelotHistory", MainWindowViewModel.SQLiteHelpers.ToDictionary(newRow));// 执行插入
int index = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("select * from Machines where Serial='PORT1' AND Station ='" +
Station + "' ", null).Tables[0].Rows[0].Field<int>("ID");
string dat_ = "SC828[" + Station + "]" + Product_.ToJsonString();
bool exists = stringQueueSerial_1.Any(item => item.ID == index && item.DAT == dat_);
if (!exists)
{
stringQueueSerial_1.Enqueue(new QueueSerial
{
ID = index,
DAT = dat_
});
}
}
}
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//获取呼叫领料单
else if (SYSAPI == "SC822")
{
try
{
DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(DAT).Copy();//反序列化
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
UserWorkOrder userWorkOrder = new UserWorkOrder();
userWorkOrder.WorkOrderTable = dataTable;
userWorkOrder.Show();
});
}
catch (Exception)
{
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
UserInf userInf = new UserInf();
userInf.Inf_DAT = "没有等待中的工艺";
userInf.Show();
userInf.Activate();
});
// LogGing.LogGingDATA("[ERR='" + ex + "']=Exception");
MainWindowViewModel.ERR_c++;
}
}//可用工单
else if (SYSAPI == "SC830")
{
try
{
Dictionary<string, object> _new = new Dictionary<string, object>();//缓存函数
_new = JsonConvert.DeserializeObject<Dictionary<string, object>>(DAT);//反序列化
string mac;
lock (MainWindowViewModel.Machines.Rows.SyncRoot)
{
DataRow drEmployee = MainWindowViewModel.Machines.Select("Station='" + Station + "' AND Serial = 'PORT1'").First();
mac = drEmployee["Name"].ToString();
drEmployee.BeginEdit();
drEmployee["ERR"] = _new.GetValue("ERR");
drEmployee["LOCK"] = _new.GetValue("LOCK");
drEmployee["Message"] = _new.GetValue("Status");
drEmployee["WorkOrder"] = _new.GetValue("Work");
drEmployee["Temperature"] = _new.GetValue("MTT");
drEmployee["WaterLevel"] = _new.GetValue("MTL");
drEmployee["Process"] = _new.GetValue("Process");
drEmployee["Step"] = _new.GetValue("Step");
drEmployee["UserButton"] = _new.GetValue("User");
if (_new.GetValue("InfoS").ToString() != "900")
{ drEmployee["UserInfoStart"] = _new.GetValue("InfoS"); }
drEmployee["UserInfo"] = _new.GetValue("Info");
drEmployee["WORK_RUN"] = _new.GetValue("RUN");
drEmployee["RUN_STEPID"] = _new.GetValue("STEPID");
drEmployee["CALL"] = _new.GetValue("CALL");
drEmployee.EndEdit();
drEmployee.AcceptChanges();
}
if (_new.GetValue("Status").ToString() != "----------")
{
Dictionary<string, object> Chart_new = new Dictionary<string, object>();//缓存函数
Chart_new.Add("WorkOrder", _new.GetValue("Work"));
Chart_new.Add("Machine", mac);
Chart_new.Add("Time", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
Chart_new.Add("MST", _new.GetValue("MST"));
Chart_new.Add("MTT", _new.GetValue("MTT"));
Chart_new.Add("MTL", _new.GetValue("MTL"));
Chart_new.Add("MTH", _new.GetValue("MTH"));
Chart_new.Add("MUT", _new.GetValue("MUT"));
Chart_new.Add("STTA", _new.GetValue("STTA"));
Chart_new.Add("STLA", _new.GetValue("STLA"));
Chart_new.Add("STTB", _new.GetValue("STTB"));
Chart_new.Add("STLB", _new.GetValue("STLB"));
Chart_new.Add("STTC", _new.GetValue("STTC"));
Chart_new.Add("STLC", _new.GetValue("STLC"));
MainWindowViewModel.SQLiteChartAdress.InsertData("Chart", Chart_new);// 执行插入
}
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++;
}
}//当前信息
else if (SYSAPI == "SC831")
{
try
{
Dictionary<string, object> _dat;
_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(DAT);
MainWindowViewModel.dt_TP = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("select * WorkorderSteps Dyelot where WorkOrder='" +
_dat.GetValue("Work") + "' AND ReDye ='" + _dat.GetValue("Re") + "'", null).Tables[0];
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//当前步骤信息
else if (SYSAPI == "SC832")
{
try
{
MainWindowViewModel.MachineLOG = DAT;
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//当前细节信息
else if (SYSAPI == "SC833")
{
try
{
Dictionary<string, object> _dat;
_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(DAT);
MonitorView.Product_DAT = MainWindowViewModel.SQLiteHelpers.ExecuteDataSet("select * from Dyelot where WorkOrder='" +
_dat.GetValue("WorkOrder") + "' AND ReDye ='" + _dat.GetValue("ReDye") + "'", null).Tables[0];
MonitorView.Product_bool = true;
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//当前领料单信息
else if (SYSAPI == "SC851")
{
try
{
Dictionary<string, object> _dat;
_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(DAT);
string[] DO = _dat.GetValue("DO").ToString().Split(',');
string[] DQ = _dat.GetValue("DQ").ToString().Split(',');
DataTable dataTable = new DataTable();
dataTable.Columns.Add("ID", Type.GetType("System.String"));
dataTable.Columns.Add("type", Type.GetType("System.String"));
dataTable.Columns.Add("DIO", Type.GetType("System.Bool"));
dataTable.Columns.Add("PLC", Type.GetType("System.String"));
for (int DOi = 0; DOi < DO.Length; DOi++)
{
DataRow newRow = dataTable.NewRow();
newRow["ID"] = DOi+2001;
newRow["type"] = "DO";
newRow["DIO"] = DO[DOi];
newRow["PLC"] = DOi + 2001;
dataTable.Rows.Add(newRow);
}
for (int DQi = 0; DQi < DO.Length; DQi++)
{
DataRow newRow = dataTable.NewRow();
newRow["ID"] = DQi + 3001;
newRow["type"] = "DQ";
newRow["DIO"] = DQ[DQi];
newRow["PLC"] = DQi + 3001;
dataTable.Rows.Add(newRow);
}
MainWindowViewModel.dt_d = dataTable;
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//数字开关表
else if (SYSAPI == "SC852")
{
try
{
Dictionary<string, object> _dat;
_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(DAT);
string[] AI = _dat.GetValue("DO").ToString().Split(',');
string[] AO = _dat.GetValue("DQ").ToString().Split(',');
DataTable dataTable = new DataTable();
dataTable.Columns.Add("ID", Type.GetType("System.String"));
dataTable.Columns.Add("type", Type.GetType("System.String"));
dataTable.Columns.Add("AIO", Type.GetType("System.Int"));
dataTable.Columns.Add("PLC", Type.GetType("System.String"));
for (int AIi = 0; AIi < AI.Length; AIi++)
{
DataRow newRow = dataTable.NewRow();
newRow["ID"] = AIi + 4001;
newRow["type"] = "DO";
newRow["AIO"] = AI[AIi];
newRow["PLC"] = AIi + 4001;
dataTable.Rows.Add(newRow);
}
for (int AOi = 0; AOi < AO.Length; AOi++)
{
DataRow newRow = dataTable.NewRow();
newRow["ID"] = AOi + 5001;
newRow["type"] = "DQ";
newRow["AIO"] = AO[AOi];
newRow["PLC"] = AOi + 5001;
dataTable.Rows.Add(newRow);
}
MainWindowViewModel.dt_a = dataTable;
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//寄存器表
else if (SYSAPI == "SC853")
{
try
{
Dictionary<string, object> _dat;
_dat = SerializeConvert.JsonDeserializeFromString<Dictionary<string, object>>(DAT);
string[] M = _dat.GetValue("M").ToString().Split(',');
DataTable dataTable = new DataTable();
dataTable.Columns.Add("ID", Type.GetType("System.String"));
dataTable.Columns.Add("type", Type.GetType("System.String"));
dataTable.Columns.Add("Value", Type.GetType("System.Double"));
dataTable.Columns.Add("PLC", Type.GetType("System.String"));
for (int Mi = 0; Mi < M.Length; Mi++)
{
DataRow newRow = dataTable.NewRow();
newRow["ID"] = Mi + 1001;
newRow["type"] = "M";
newRow["Value"] = M[Mi];
newRow["PLC"] = Mi + 1001;
dataTable.Rows.Add(newRow);
}
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//缓存表
else if (SYSAPI == "SC854")
{
try
{
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//程序设置表
else if (SYSAPI == "SC855")
{
try
{
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//系统设置表
else if (SYSAPI == "SC859")
{
try
{
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//信息
else if (SYSAPI == "SC910")
{
try
{
MainWindowViewModel.SQLiteHelpers.Update("WorkOrder", new Dictionary<string, object> { { "State", 109 } },
"WorkOrder ='" + DAT + "'", null);
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//发布失败
else if (SYSAPI == "SC911")
{
try
{
MainWindowViewModel.SQLiteHelpers.Update("WorkOrder", new Dictionary<string, object> { { "State", 119 } },
"WorkOrder ='" + DAT + "'", null);
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//细节错误
else if (SYSAPI == "SC921")
{
try
{
}
catch (Exception ex) { LogGing.LogGingDATA("[ERR='" + ex + "']=Exception"); MainWindowViewModel.ERR_c++; }
}//错误
else if (SYSAPI == "SC980")
{
MessageBox.Show(DAT, "SCCM", MessageBoxButton.OK, MessageBoxImage.Question);
}
}
}
return EasyTask.CompletedTask; ;
};
await portclient.SetupAsync(new TouchSocketConfig()
.SetMaxBufferSize(1024 * 1024 * 10)
.SetSerialPortOption(new SerialPortOption()
{
BaudRate = BAUD,//波特率
DataBits = 8,//数据位
Parity = System.IO.Ports.Parity.None,//校验位
PortName = com,//COM
StopBits = System.IO.Ports.StopBits.One,//停止位
})
.SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) })
.ConfigurePlugins(a =>
{
//a.Add<MyPlugin>();
}
));
try
{
await portclient.ConnectAsync();
}
catch (Exception ex) { LogGing.ERRDATA(ex); }
}
public static async Task PortClient2(SerialPortClient portclient, string com, int BAUD)
{
//var client = new SerialPortClient();
portclient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到端口
portclient.Connected = (client, e) => { return EasyTask.CompletedTask; };//成功连接到端口
portclient.Closing = (client, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
portclient.Closed = (client, e) => { return EasyTask.CompletedTask; };//从端口断开连接,当连接不成功时不会触发。
portclient.Received = (client, e) =>
{
_responseEvent2.Set();
string[] sArray = Regex.Split(e.ByteBlock.Span.ToString(Encoding.UTF8),
@"\n", RegexOptions.IgnoreCase);
return EasyTask.CompletedTask; ;
};
await portclient.SetupAsync(new TouchSocketConfig()
.SetSerialPortOption(new SerialPortOption()
{
BaudRate = BAUD,//波特率
DataBits = 8,//数据位
Parity = System.IO.Ports.Parity.None,//校验位
PortName = com,//COM
StopBits = System.IO.Ports.StopBits.One,//停止位
})
.SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) })
.ConfigurePlugins(a =>
{
//a.Add<MyPlugin>();
}));
try
{
await portclient.ConnectAsync();
}
catch (Exception ex) { LogGing.ERRDATA(ex); }
}
public static async Task PortClient3(SerialPortClient portclient, string com, int BAUD)
{
//var client = new SerialPortClient();
portclient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到端口
portclient.Connected = (client, e) => { return EasyTask.CompletedTask; };//成功连接到端口
portclient.Closing = (client, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
portclient.Closed = (client, e) => { return EasyTask.CompletedTask; };//从端口断开连接,当连接不成功时不会触发。
portclient.Received = (client, e) =>
{
_responseEvent3.Set();
string[] sArray = Regex.Split(e.ByteBlock.Span.ToString(Encoding.UTF8),
@"\n", RegexOptions.IgnoreCase);
return EasyTask.CompletedTask; ;
};
await portclient.SetupAsync(new TouchSocketConfig()
.SetSerialPortOption(new SerialPortOption()
{
BaudRate = BAUD,//波特率
DataBits = 8,//数据位
Parity = System.IO.Ports.Parity.None,//校验位
PortName = com,//COM
StopBits = System.IO.Ports.StopBits.One,//停止位
})
.SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) })
.ConfigurePlugins(a =>
{
//a.Add<MyPlugin>();
}));
try
{
await portclient.ConnectAsync();
}
catch (Exception ex) { LogGing.ERRDATA(ex); }
}
public static async Task PortClient4(SerialPortClient portclient, string com, int BAUD)
{
//var client = new SerialPortClient();
portclient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到端口
portclient.Connected = (client, e) => { return EasyTask.CompletedTask; };//成功连接到端口
portclient.Closing = (client, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
portclient.Closed = (client, e) => { return EasyTask.CompletedTask; };//从端口断开连接,当连接不成功时不会触发。
portclient.Received = (client, e) =>
{
_responseEvent4.Set();
string[] sArray = Regex.Split(e.ByteBlock.Span.ToString(Encoding.UTF8),
@"\n", RegexOptions.IgnoreCase);
return EasyTask.CompletedTask; ;
};
await portclient.SetupAsync(new TouchSocketConfig()
.SetSerialPortOption(new SerialPortOption()
{
BaudRate = BAUD,//波特率
DataBits = 8,//数据位
Parity = System.IO.Ports.Parity.None,//校验位
PortName = com,//COM
StopBits = System.IO.Ports.StopBits.One,//停止位
})
.SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) })
.ConfigurePlugins(a =>
{
//a.Add<MyPlugin>();
}));
try
{
await portclient.ConnectAsync();
}
catch (Exception ex) { LogGing.ERRDATA(ex); }
}
public static readonly ManualResetEventSlim _responseEvent = new ManualResetEventSlim(false);
public static readonly ManualResetEventSlim _responseEvent2 = new ManualResetEventSlim(false);
public static readonly ManualResetEventSlim _responseEvent3 = new ManualResetEventSlim(false);
public static readonly ManualResetEventSlim _responseEvent4 = new ManualResetEventSlim(false);
/// <summary>
/// 发送指令并等待响应,超时时间为500ms
/// </summary>
/// <param name="command">要发送的指令字节数组</param>
/// <returns>从机的响应数据,超时则为null</returns>
public static void SendCommandAndWait(SerialPortClient serialPortClients, string command)
{
try
{
// var t = CRCcheck16.ToCRC16(command);
_responseEvent.Reset();
serialPortClients.Send(command); // 发送指令
// 等待500毫秒或直到收到响应
_responseEvent.Wait(TimeSpan.FromMilliseconds(1000));
if (!_responseEvent.IsSet)
{
//清机台状态
string Station = ClipBetween(command, '[', ']');
lock (MainWindowViewModel.Machines.Rows.SyncRoot)
{
DataRow drEmployee = MainWindowViewModel.Machines.Select("Station='" +
Station + "' AND Serial = 'PORT1'").First();
if (drEmployee.Field<int>("State") != 800)
{
drEmployee.BeginEdit();
drEmployee["State"] = "800";
drEmployee["WorkOrder"] = "------";
drEmployee["Dyelot"] = "";
drEmployee["Temperature"] = 0.0;
drEmployee["WaterLevel"] = 0.0;
drEmployee["Process"] = "";
drEmployee["Step"] = "";
drEmployee["Message"] = "";
drEmployee["SYSKEY"] = "";
drEmployee["WORK_RUN"] = "-1";
drEmployee["ERR"] = false;
drEmployee.EndEdit();
drEmployee.AcceptChanges();
}
}
}
// 重置事件状态
_responseEvent.Set();
}
catch (Exception) { }
}
public static void SendCommandAndWait2(SerialPortClient serialPortClients, string command)
{
try
{
_responseEvent2.Reset();
serialPortClients.Send(command); // 发送指令
// 等待500毫秒或直到收到响应
_responseEvent2.Wait(TimeSpan.FromMilliseconds(1000));
// 重置事件状态
_responseEvent2.Set();
}
catch (Exception) { }
}
public static void SendCommandAndWait3(SerialPortClient serialPortClients, string command)
{
try
{
_responseEvent3.Reset();
serialPortClients.Send(command); // 发送指令
// 等待500毫秒或直到收到响应
_responseEvent3.Wait(TimeSpan.FromMilliseconds(1000));
// 重置事件状态
_responseEvent3.Set();
}
catch (Exception) { }
}
public static void SendCommandAndWait4(SerialPortClient serialPortClients, string command)
{
try
{
_responseEvent4.Reset();
serialPortClients.Send(command); // 发送指令
// 等待500毫秒或直到收到响应
_responseEvent4.Wait(TimeSpan.FromMilliseconds(1000));
// 重置事件状态
_responseEvent4.Set();
}
catch (Exception) { }
}
}
}