HKC/DM_Weight/Port/ModbusHelper.cs

229 lines
9.0 KiB
C#
Raw Normal View History

2024-12-16 16:44:02 +08:00
using DM_Weight.Finger;
using DM_Weight.msg;
using DM_Weight.ViewModels;
using log4net;
using log4net.Repository.Hierarchy;
using Modbus.Device;
using Polly;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Speech.Synthesis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static DM_Weight.Port.KeepAliveSocket;
namespace DM_Weight.Port
{
public class ModbusHelper
{
private static ModbusHelper instance;
private ModbusIpMaster master;
private Socket socket;
private TcpClient client;
private readonly ILog logger = LogManager.GetLogger(typeof(CheckOrderNewWindowViewModel));
string ip = ConfigurationManager.AppSettings["modbusIp"].ToString();
int port = Convert.ToInt32(ConfigurationManager.AppSettings["modbusPort"]);
2024-12-16 16:44:02 +08:00
private static object _lock = new object();
public static bool BoxOperate { get; set; }
private ModbusHelper()
{
logger.Info("ModbusHelper");
2024-12-16 16:44:02 +08:00
socket = KeepALiveSocket.MakeKeepALiveSocket(ip, port);
2024-12-16 16:44:02 +08:00
//socket = CreateSocket();
client = new TcpClient();
client.Client = socket;
master = ModbusIpMaster.CreateIp(client);
}
public static ModbusHelper GetInstance()
{
2024-12-16 16:44:02 +08:00
lock (_lock)
{
2024-12-16 16:44:02 +08:00
if (instance == null)
{
instance = new ModbusHelper();
}
return instance;
}
}
private void SetModusIpMaster()
{
logger.Info("SetModusIpMaster");
socket = KeepALiveSocket.MakeKeepALiveSocket(ip, port);
client = new TcpClient();
client.Client = socket;
master = ModbusIpMaster.CreateIp(client);
}
public bool[] GetAllBoxState()
{
//bool[] bools = Policy.Handle<Exception>()
// .Retry(3, (exception, retryCount) =>
// {
// this.Dispose();
// //Debug.WriteLine($"获取所有箱子门状态出错,第{retryCount}次重试", exception);
// logger.Info($"获取所有箱子门状态出错,第{retryCount}次重试, 异常信息{exception}");
// Thread.Sleep(50);
// this.SetModusIpMaster();
// BoxOperate = false;
// // return TimeSpan.FromSeconds (1);
// }).Execute<bool[]>(() =>
// {
// bool[] flags = new bool[18];
// try
// {
// if (master == null)
// {
// this.SetModusIpMaster();
// }
// var result = master.ReadInputRegisters(1, 0x0033, 2);
// var r1 = Convert.ToString(((int)result[0] >> 14) | ((int)result[1] << 2), 2).PadLeft(18, '0');
// var r2 = r1.ToCharArray();
// logger.Info("r2=>" + string.Join(", ", r2));
// //var r2=new char[18] { '0','0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };
// for (int i = 0; i < 18; i++)
// {
// flags[i] = r2[17 - i] == '1' ? true : false;
// }
// logger.Info($"获取所有箱子门状态返回:{string.Join(',', flags)};");
// }
// catch (Exception)
// {
// this.Dispose();
// //Debug.WriteLine($"获取所有箱子门状态出错,第{retryCount}次重试", exception);
// logger.Info($"获取所有箱子门状态出错,第{retryCount}次重试, 异常信息{exception}");
// Thread.Sleep(50);
// this.SetModusIpMaster();
// BoxOperate = false;
// }
// return flags;
// });
2024-12-16 16:44:02 +08:00
lock (_lock)
{
2024-12-16 16:44:02 +08:00
bool successFlag = true;
bool[] bools = new bool[18];
int iCount = 0;
do
{
2024-12-16 16:44:02 +08:00
try
{
2024-12-16 16:44:02 +08:00
bool[] flags = new bool[18];
if (master == null)
{
this.SetModusIpMaster();
}
var result = master.ReadInputRegisters(1, 0x0033, 2);
var r1 = Convert.ToString(((int)result[0] >> 14) | ((int)result[1] << 2), 2).PadLeft(18, '0');
var r2 = r1.ToCharArray();
logger.Info("r2=>" + string.Join(", ", r2));
//var r2=new char[18] { '0','0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };
for (int i = 0; i < 18; i++)
{
bools[i] = r2[17 - i] == '1' ? true : false;
}
logger.Info($"获取所有箱子门状态返回:{string.Join(',', bools)};");
successFlag = true;
}
2024-12-16 16:44:02 +08:00
catch (Exception exception)
{
2024-12-16 16:44:02 +08:00
if (iCount >= 3)
break;
iCount++;
successFlag = false;
this.Dispose();
//Debug.WriteLine($"获取所有箱子门状态出错,第{retryCount}次重试", exception);
logger.Info($"获取所有箱子门状态出错,第{iCount}次重试,异常信息{exception}");
Thread.Sleep(500);
this.SetModusIpMaster();
BoxOperate = false;
FingerprintUtil.FingerDisconnect();
}
2024-12-16 16:44:02 +08:00
} while (!successFlag);
return bools;
}
}
2024-11-05 08:49:56 +08:00
public bool OpenBoxDoor(int boxNum)
{
2024-12-16 16:44:02 +08:00
lock (_lock)
{
2024-12-16 16:44:02 +08:00
BoxOperate = true;
//if (ConfigurationManager.AppSettings["test"]!=null&& ConfigurationManager.AppSettings["test"].ToString()=="Y")
//{
// return true;
//}
bool bFlag = false;
Thread.Sleep(50);
Policy.Handle<Exception>().Retry(3, ((exception, retryCount) =>
{
this.Dispose();
//Debug.WriteLine($"打开箱子出错,第{retryCount}次重试", exception);
logger.Info($"打开箱子出错,第{retryCount}次重试,异常信息{exception}");
//SpeakAsync("药箱连接失败,正在尝试重新打开");
Thread.Sleep(500);
this.SetModusIpMaster();
//return TimeSpan.FromSeconds (1);
})).Execute(() =>
{
logger.Info($"正在打开{boxNum}号药箱");
master.WriteSingleRegister(1, (ushort)boxNum, 20);
logger.Info($"开门指令已发送{(ushort)boxNum}");
SpeakAsync("请及时关闭药箱");
//Console.WriteLine($"开门指令已发送{(ushort)boxNum}");
bFlag = true;
FingerprintUtil.FingerDisconnect();
});
return bFlag;
}
}
private void Dispose()
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
client.Close();
master.Dispose();
}
private static SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
public static void SpeakAsync(string textinfo)
{
2024-12-16 16:44:02 +08:00
speechSynthesizer.Rate = 2;
speechSynthesizer.SpeakAsync(textinfo);
}
private Socket CreateSocket()
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string serverIp = "127.0.0.1"; // 服务器IP地址
int port = 4002; // 服务器端口
IPAddress serverAddress = IPAddress.Parse(serverIp);
IPEndPoint remoteEP = new IPEndPoint(serverAddress, port);
clientSocket.Connect(remoteEP);
if (clientSocket.Connected)
{
// 发送数据
//byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
//clientSocket.Send(msg);
// 关闭socket
//clientSocket.Shutdown(SocketShutdown.Both);
//clientSocket.Close();
}
return clientSocket;
}
}
}