213 lines
8.4 KiB
C#
213 lines
8.4 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 = 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;
|
|
// });
|
|
bool successFlag = true;
|
|
bool[] bools = new bool[18];
|
|
int iCount = 0;
|
|
do
|
|
{
|
|
try
|
|
{
|
|
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;
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
if (iCount >= 3)
|
|
break;
|
|
iCount++;
|
|
successFlag = false;
|
|
this.Dispose();
|
|
//Debug.WriteLine($"获取所有箱子门状态出错,第{retryCount}次重试", exception);
|
|
logger.Info($"获取所有箱子门状态出错,第{iCount}次重试,异常信息{exception}");
|
|
Thread.Sleep(500);
|
|
this.SetModusIpMaster();
|
|
BoxOperate = false;
|
|
}
|
|
} while (!successFlag);
|
|
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(500);
|
|
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;
|
|
}
|
|
}
|
|
}
|