154 lines
		
	
	
		
			5.2 KiB
		
	
	
	
		
			C#
		
	
	
	
			
		
		
	
	
			154 lines
		
	
	
		
			5.2 KiB
		
	
	
	
		
			C#
		
	
	
	
using DM_Weight.Finger;
 | 
						|
using DM_Weight.msg;
 | 
						|
using DM_Weight.util;
 | 
						|
using DM_Weight.ViewModels;
 | 
						|
using log4net;
 | 
						|
using Mina.Core.Future;
 | 
						|
using Mina.Core.Session;
 | 
						|
using Mina.Filter.Codec;
 | 
						|
using Mina.Filter.Logging;
 | 
						|
using Mina.Transport.Socket;
 | 
						|
using Prism.Events;
 | 
						|
using System;
 | 
						|
using System.Collections.Generic;
 | 
						|
using System.Configuration;
 | 
						|
using System.Linq;
 | 
						|
using System.Net;
 | 
						|
using System.Speech.Synthesis;
 | 
						|
using System.Text;
 | 
						|
using System.Threading;
 | 
						|
using System.Threading.Tasks;
 | 
						|
 | 
						|
namespace DM_Weight.Port
 | 
						|
{
 | 
						|
    public class SocketHelper
 | 
						|
    {
 | 
						|
        private readonly ILog logger = LogManager.GetLogger(typeof(SocketHelper));
 | 
						|
        AsyncSocketConnector acceptor = new AsyncSocketConnector();
 | 
						|
        IConnectFuture iConnectFuture;
 | 
						|
        public bool OpenStatus = false;
 | 
						|
        public bool ConnectedStatus = false;
 | 
						|
        //多线程退出标识
 | 
						|
        public bool IsMultiThread = false;
 | 
						|
        string ip = ConfigurationManager.AppSettings["modbusIp"].ToString();
 | 
						|
        int port = Convert.ToInt32(ConfigurationManager.AppSettings["modbusPort"]);
 | 
						|
        IEventAggregator _eventAggregator;
 | 
						|
        FingerprintUtil _fingerprintUtil;
 | 
						|
        public DateTime dateTime { get; set; } = DateTime.Now;
 | 
						|
        public SocketHelper(IEventAggregator eventAggregator, FingerprintUtil fingerprintUtil)
 | 
						|
        {
 | 
						|
            _fingerprintUtil = fingerprintUtil;
 | 
						|
            _eventAggregator = eventAggregator;
 | 
						|
            acceptor.ExceptionCaught += (o, e) =>
 | 
						|
            {
 | 
						|
                logger.Error($"网口通信超时:{e.Exception}");
 | 
						|
                AlertMsg alertMsg = new AlertMsg
 | 
						|
                {
 | 
						|
                    Message = $"网口通信超时,正在重试!",
 | 
						|
                    Type = MsgType.ERROR
 | 
						|
                };
 | 
						|
                _eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
 | 
						|
            };
 | 
						|
 | 
						|
            //acceptor.FilterChain.AddLast("logger", new LoggingFilter());
 | 
						|
            acceptor.FilterChain.AddLast("encoding", new ProtocolCodecFilter(new MyMinaCodecFactory()));
 | 
						|
 | 
						|
            acceptor.SessionIdle += (o, e) => logger.Info("IDLE " + e.Session.GetIdleCount(e.IdleStatus));
 | 
						|
 | 
						|
            acceptor.MessageReceived += (o, e) =>
 | 
						|
            {
 | 
						|
                OpenStatus = (bool)e.Message;
 | 
						|
                logger.Info("MessageReceived>>>>>>>>>>>>>>>>" + OpenStatus);
 | 
						|
            };
 | 
						|
 | 
						|
            acceptor.SessionClosed += new EventHandler<IoSessionEventArgs>(SessionCloseMethod);
 | 
						|
 | 
						|
            //acceptor.SessionClosed += (o, e) =>
 | 
						|
            //{
 | 
						|
            //    logger.Info($"SessionClosed;ExitFlag:{ExitFlag}");
 | 
						|
            //    //Task.Delay(50).Wait();
 | 
						|
            //    if (!ExitFlag)
 | 
						|
            //    {
 | 
						|
            //        SocketConnect();
 | 
						|
            //        Task.Factory.StartNew(() =>
 | 
						|
            //        {
 | 
						|
            //            _fingerprintUtil.FingerDisconnect();
 | 
						|
            //        });
 | 
						|
            //    }
 | 
						|
            //};
 | 
						|
            this.SocketConnect();
 | 
						|
        }
 | 
						|
        int i = 0;
 | 
						|
        public void SocketConnect()
 | 
						|
        {
 | 
						|
            Thread.Sleep(50);
 | 
						|
            i++;
 | 
						|
            iConnectFuture = acceptor.Connect(new IPEndPoint(IPAddress.Parse(ip), port)).Await();
 | 
						|
            logger.Info($"第{i}次连接结果:{iConnectFuture.Connected.ToString()}");
 | 
						|
            if (!iConnectFuture.Connected)
 | 
						|
            {
 | 
						|
                if (i <= 3)
 | 
						|
                {
 | 
						|
                    //没连上会再连两次
 | 
						|
                    SocketConnect();
 | 
						|
                }
 | 
						|
                else
 | 
						|
                {
 | 
						|
                    logger.Error($"尝试{i}次连接后均连接不上");
 | 
						|
 | 
						|
                    //AlertMsg alertMsg = new AlertMsg
 | 
						|
                    //{
 | 
						|
                    //    Message = $"网口连接断开!",
 | 
						|
                    //    Type = MsgType.ERROR
 | 
						|
                    //};
 | 
						|
                    //_eventAggregator.GetEvent<SnackbarEvent>().Publish(alertMsg);
 | 
						|
                }
 | 
						|
            }
 | 
						|
            else
 | 
						|
            {
 | 
						|
                i = 0;
 | 
						|
            }
 | 
						|
            ConnectedStatus = iConnectFuture.Connected;
 | 
						|
        }
 | 
						|
 | 
						|
        private void SessionCloseMethod(System.Object o, IoSessionEventArgs e)
 | 
						|
        {
 | 
						|
            logger.Info($"SessionClosed");
 | 
						|
            SocketConnect();
 | 
						|
            Task.Factory.StartNew(() =>
 | 
						|
            {
 | 
						|
                _fingerprintUtil.FingerDisconnect();
 | 
						|
            });
 | 
						|
        }
 | 
						|
        public void SocketDisConnect()
 | 
						|
        {
 | 
						|
 | 
						|
            try
 | 
						|
            {
 | 
						|
                acceptor.SessionClosed -= new EventHandler<IoSessionEventArgs>(SessionCloseMethod);
 | 
						|
                iConnectFuture.Session.CloseNow();
 | 
						|
            }
 | 
						|
            catch (Exception ex)
 | 
						|
            {
 | 
						|
                logger.Info($"SocketDisConnect异常{ex.Message}");
 | 
						|
            }
 | 
						|
        }
 | 
						|
 | 
						|
        public void SendMessage(MyBaseMessage baseMessage)
 | 
						|
        {
 | 
						|
            if (!ConnectedStatus)
 | 
						|
            {
 | 
						|
                SocketConnect();
 | 
						|
            }
 | 
						|
            iConnectFuture.Session.Write(baseMessage);
 | 
						|
            logger.Info($"SendMessage:{baseMessage.functionCode},delay:{baseMessage.delay},lockNo:{baseMessage.lockNo}");
 | 
						|
        }
 | 
						|
        public SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
 | 
						|
        public void SpeakAsync(string textinfo)
 | 
						|
        {
 | 
						|
            speechSynthesizer.Rate = 2;
 | 
						|
            speechSynthesizer.SpeakAsync(textinfo);
 | 
						|
        }
 | 
						|
    }
 | 
						|
}
 |