Files

134 lines
4.2 KiB
C#

using Cowain.Bake.Common;
using Cowain.Bake.Common.Core;
using Cowain.Bake.Communication.Interface;
using Cowain.Bake.Communication.Models;
using Cowain.Bake.Communication.Sokects;
using HslCommunication;
using Newtonsoft.Json;
using Prism.Services.Dialogs;
using System;
using System.Threading;
using Unity;
namespace Cowain.Bake.Communication.Scan
{
public class Honeywell : IScanCodeBase
{
string DataPack = "";
TcpSocketClient tcpClient = null;
IUnityContainer _unityContainer;
MessageEventWaitHandle<string> messageEvent { get; set; }
public Honeywell(IUnityContainer unityContainer, IDialogService dialogService) : base(unityContainer, dialogService)
{
_unityContainer = unityContainer;
messageEvent = new MessageEventWaitHandle<string>(false, EventResetMode.ManualReset);
}
public override bool Connect()
{
tcpClient = new TcpSocketClient(Ip, Port);
tcpClient.ValueChanged += (sender, e) =>
{
IsConnect = ((TcpSocketClient)sender).IsConnected;
SetStatus(Id, IsConnect);
};
tcpClient.ReceivedString += TcpClient_ReceivedString; ;
tcpClient.ConnectServer();
return true;
}
public override void GetJsonParam(string param)
{
try
{
dynamic d = JsonConvert.DeserializeObject<dynamic>(param);
Ip = d.Ip;
Port = d.Port;
Command = d.Command;
FilterRegex = d.FilterCodes; //去掉返回不要的码
CloseCommand = d.CloseCommand;
if (string.IsNullOrEmpty(Ip)
|| string.IsNullOrEmpty(Command))
{
LogHelper.Instance.GetCurrentClassError("扫码枪解析出错:" + param);
}
}
catch (Exception ex)
{
LogHelper.Instance.GetCurrentClassError($"扫码枪解析出错:{param},{ex} ");
}
}
private void TcpClient_ReceivedString(string obj)
{
messageEvent.Set(obj);
}
public override void Close()
{
tcpClient.ConnectClose();
}
private bool isConnect;
public override bool IsConnect
{
get
{
isConnect = tcpClient.IsConnected;
return isConnect;
}
set
{
isConnect = value;
}
}
public override OperateResult<string> ReadCode()
{
OperateResult plcResult;
ExOperateResult<string> result = new ExOperateResult<string>()
{
IsSuccess = false
};
for (int i = 0; i < Global.MAX_READS; i++)
{
var array = Command.Split('+');
var command = array[0];
if (array.Length > 1 && array[1] == "NewLine")
{
plcResult = tcpClient.SendString(command + Environment.NewLine);
}
else
{
plcResult = tcpClient.SendString(command);
}
result.IsSuccess = plcResult.IsSuccess;
result.Message = plcResult.Message;
result.ErrorCode = plcResult.ErrorCode;
if (!result.IsSuccess)
{
result.Message = "发送数据失";
LogHelper.Instance.Error($"发送数据失败,发送数据:{Command}");
continue;
}
DataPack = messageEvent.GetMessage(1 * Global.SECONDS_TO_MILLISCONDS);//"0\r\n"
if (string.IsNullOrEmpty(DataPack)) //超时才返回为空
{
result.Message = "失败";
result.IsSuccess = false;
result.Content = "操作超时!";
}
result.Content = DataPack?.Replace("\r\n","");
break;
}
return result;
}
}
}