HKC/DM_Weight/Port/ModbusHelper.cs

186 lines
7.2 KiB
C#

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"]);
public static bool BoxOperate { get; set; }
private ModbusHelper()
{
logger.Info("ModbusHelper");
socket = KeepALiveSocket.MakeKeepALiveSocket(ip, port);
//socket = CreateSocket();
client = new TcpClient();
client.Client = socket;
master = ModbusIpMaster.CreateIp(client);
}
public static ModbusHelper GetInstance()
{
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 = { true };
//if (BoxOperate)
//{
//if (ConfigurationManager.AppSettings["test"] != null && ConfigurationManager.AppSettings["test"].ToString() == "Y")
//{
// return new bool[] { false,false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false};
//}
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];
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)};");
//bool allFalse = Array.TrueForAll(flags, b => b == false);
//if (!allFalse)
//{
// Task.Delay(500);
// Task.Factory.StartNew(async () =>
// {
// SpeakAsync("药箱已打开,请及时关闭");
// await Task.Delay(15000);
// });
//}
//else
//{
// BoxOperate = false;
//}
return flags;
});
//}
return bools;
}
public bool OpenBoxDoor(int boxNum)
{
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(50);
this.SetModusIpMaster();
//return TimeSpan.FromSeconds (1);
})).Execute(() =>
{
logger.Info($"正在打开{boxNum}号药箱");
master.WriteSingleRegister(1, (ushort)boxNum, 0);
logger.Info($"开门指令已发送{(ushort)boxNum}");
SpeakAsync("药箱已打开,请及时关闭");
//Console.WriteLine($"开门指令已发送{(ushort)boxNum}");
bFlag = true;
});
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)
{
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;
}
}
}