using LB_VisionProcesses.Communicators;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
namespace LB_VisionProcesses.Communicators
{
[Serializable]
public class CommunicatorConfig : IProcess
{
///
/// 通讯集合(Key:通讯名,Value:通讯句柄)
///
public ConcurrentDictionary dicCommunicators { get; set; }
public CommunicatorConfig(ConcurrentDictionary dicCommunicators)
{
this.dicCommunicators = dicCommunicators;
strProcessName = "通讯测试";
strProcessClass = "LB_VisionProcesses.Communicators.CommunicatorConfig";
Params.Inputs.Add("通讯口名", "");
Params.Inputs.Add("通讯类型", CommunicatorType.Receiver);
Params.Inputs.Add("是否启用CRC校验", false);
Params.Inputs.Add("通讯消息", "");
Params.Outputs.Add("收到消息", "");
}
///
/// 加载算法
///
/// 完整路径带.json
///
public override bool Load(string fullPath = null)
{
try
{
if (string.IsNullOrEmpty(fullPath))
return false;
if (!fullPath.Contains(".json"))
{
Debug.WriteLine("文件路径不完整");
return false;
}
if (string.IsNullOrEmpty(fullPath) || fullPath.Trim() == "")
{
Debug.WriteLine("文件路径不完整");
return false;
}
// 获取不带文件名的目录路径
string directoryPath = Path.GetDirectoryName(fullPath);
strProcessName = Path.GetFileNameWithoutExtension(fullPath);
if (!File.Exists(fullPath))
{
Debug.WriteLine("文件不存在创建空文件");
Save(directoryPath);
return true;
}
string strJson = string.Empty;
using (StreamReader streamReader = new StreamReader(fullPath, Encoding.UTF8))
{
strJson = streamReader.ReadToEnd();
streamReader.Close();
}
Params = JsonConvert.DeserializeObject(strJson);
if (Params == null)
return false;
Params.FixDeserializedData();
return true;
}
catch { return false; }
}
///
/// 保存算法
///
/// 不带.json
///
public override bool Save(string filePath = null)
{
try
{
if (string.IsNullOrEmpty(filePath) || filePath.Trim() == "")
{
Debug.WriteLine("文件路径不完整");
return false;
}
string strJson = string.Empty;
var settings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
// 自定义缩进(4空格)
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
}
};
strJson = JsonConvert.SerializeObject(Params, settings);
Params = JsonConvert.DeserializeObject(strJson);
if (Params == null)
return false;
//判断文件夹是否存在,防呆输入为文件名称
if (!Directory.Exists(filePath))
{
try
{
Directory.CreateDirectory(filePath);
}
catch (Exception)
{ }
}
File.WriteAllText(filePath + "//" + strProcessName + ".json", strJson, Encoding.UTF8);
return true;
}
catch { return false; }
}
public override bool Run()
{
try
{
InitRunParams();
Params.Outputs["收到消息"] = "";
string CommunicatorName = Params.Inputs["通讯口名"].ToString();
if (!dicCommunicators.ContainsKey(CommunicatorName))
{
Msg = $"通讯口[{CommunicatorName}]不存在";
Result = false;
return Result;
}
BaseCommunicator BaseCommunicator = dicCommunicators[CommunicatorName];
if (BaseCommunicator == null)
{
Msg = $"通讯口[{CommunicatorName}]未实例化";
Result = false;
return Result;
}
if (!BaseCommunicator.bConnected)
{
Msg = $"通讯口[{CommunicatorName}]未连接";
Result = false;
return Result;
}
if (!Enum.TryParse(Params.Inputs["通讯类型"].ToString(), out CommunicatorType CommunicatorType))
{
Msg = $"通讯口[{CommunicatorName}]通讯类型不正确,值为:{Params.Inputs["通讯类型"].ToString()}";
Result = false;
return Result;
}
if (Params.Inputs["通讯消息"] is List)
{
List listMsg = (List)Params.Inputs["通讯消息"];
if (listMsg.Count > 0)
Params.Inputs["通讯消息"] = string.Join(',', listMsg);
}
string SendMsg = Params.Inputs["通讯消息"].ToString();
string ShouldReceiveMsg = Params.Inputs["通讯消息"].ToString();
bool CheckRule = Convert.ToBoolean(Params.Inputs["是否启用CRC校验"]);
switch (CommunicatorType)
{
case CommunicatorType.Sender:
if (CheckRule)
{
byte[] HexByte = BaseCommunicator.strToHexByte(SendMsg);
ushort crcHexByte = BaseCommunicator.CRC16Calculate(HexByte, HexByte.Length);
string crcString = crcHexByte.ToString("X4");
//HexByte = strToHexByte(strSendMsg + crcString);
SendMsg = SendMsg + crcString;
}
Result = BaseCommunicator.SendMessage(SendMsg);
break;
case CommunicatorType.Receiver:
string receiveMsg = BaseCommunicator.ReceiveMsg();
Params.Outputs["收到消息"] = receiveMsg;
//不设置消息时默认PASS
if (ShouldReceiveMsg == "")
{
Result = true;
return Result;
}
if (!receiveMsg.Contains(ShouldReceiveMsg))
{
Msg = $"通讯口[{CommunicatorName}]收到消息不全,应包含{ShouldReceiveMsg}";
Result = false;
}
break;
default:
Msg = $"通讯类型只支持发送消息和接收消息!";
Result = false;
break;
}
}
catch (Exception ex)
{
Msg = $"通讯异常,原因是:{ex.Message}";
Result = false;
}
return Result;
}
public override void InitRunParams()
{
Result = true;
Msg = "";
if (Record != null)
Record.Dispose();
}
public override void Dispose()
{
return;
}
public override object Clone()
{
return MemberwiseClone();
}
}
}