123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379 |
- using Cksoft.Data;
- using Cksoft.Data.Repository;
- using DllEapDal;
- using DllEapEntity;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace DllEapBll
- {
- public class AppletStatusCollectionBll
- {
- ILogger<AppletStatusCollectionBll> logger;
- public IConfiguration Configuration { get; set; }
- List<Machine> CurrMachine = new List<Machine>();
- List<Telnet> CurrTelnet = new List<Telnet>();
- IDatabase db = null;
- public AppletStatusCollectionBll(ILogger<AppletStatusCollectionBll> logger, IConfiguration configuration)
- {
- Configuration = configuration;
- this.logger = logger;
- }
- public static void AppletCollection(ref string errorinfo)
- {
- //AppletStatusCollectionBll bll = new AppletStatusCollectionBll(logger);
- //bll.DoCollection(ref errorinfo);
- }
- public void DoCollection(ref string errorinfo)
- {
- try
- {
- //LogHelper<EapDataCollectBll>.LogInfo("开始处理机台小程序运行状态---------", "EapAsync", string.Empty);
- int timeout = Convert.ToInt32(Configuration["timeout"]);
- var interval = Convert.ToInt32(Configuration["CheckStatusInterval"]);
- Task.Run(() =>
- {
- try
- {
- while (true)
- {
- StringBuilder stringBuilder = new StringBuilder();
- logger.LogError("开始处理机台小程序运行状态---------");
- IEnumerable<DllEapEntity.Machine> models = null;
- using (IDatabase db = DbFactory.Base("eap"))
- {
- var dal = new MachineDal(db);
- string info = "";
- //IEnumerable<DllEapEntity.Machine> models = dal.Get(1, 10000, "ID", "", " and a.id in(2,14,268)", info);
- models = dal.Get(1, 10000, "ID", "", "", ref info);
- }
- List<DllEapEntity.Machine> ttlist = null;
- int result = 0;
- #region
- //foreach (var item in models)
- //{
- // var telnet = new Telnet("192.168.124.93", 1234, timeout, logger, item);
- // string err = string.Empty;
- // telnet.ConnectTcp(ref err);
- //}
- #endregion
- #region
- List<int> idsOne = new List<int>();
- List<int> idsTwo = new List<int>();
- var tt = Parallel.ForEach(models,
- new ParallelOptions { MaxDegreeOfParallelism = 1000 },
- item =>
- {
- if (CheckIPFormat(item.IPAddress))
- {
- string error = "";
- Telnet p = new Telnet(item.IPAddress, 5888, timeout, logger, item);
- if (p.ConnectTcp(ref error))
- {
- if (item.AppletS != 1)
- {
- idsOne.Add(item.ID);
- }
- logger.LogError(item.FCode + "已开启小程序");
- }
- else
- {
- if (item.AppletS != -1)
- {
- idsTwo.Add(item.ID);
- }
- logger.LogError(item.FCode + "未开启小程序");
- }
- }
- Thread.Sleep(10);
- });
- if (tt.IsCompleted)
- {
- if (idsOne.Count >= 1)
- {
- stringBuilder.AppendLine($" update machine set AppletS=1 where id in ({string.Join(",", idsOne.ConvertAll<string>(new Converter<int, string>(m => m.ToString())).ToArray())}); ");
- }
- if (idsTwo.Count >= 1)
- {
- stringBuilder.AppendLine($" update machine set AppletS=-1 where id in ({string.Join(",", idsTwo.ConvertAll<string>(new Converter<int, string>(m => m.ToString())).ToArray())}); ");
- }
- //LogHelper<EapDataCollectBll>.LogInfo("结束处理机台小程序运行状态---------", "EapAsync", stringBuilder.ToString());
- string strsql = stringBuilder.ToString();
- if (!string.IsNullOrEmpty(strsql))
- {
- logger.LogError("修改机台运行状态: " + strsql);
- UpdateMachineStatus(strsql);
- }
- logger.LogError("完成处理机台小程序运行状态---------");
- }
- #endregion
- Thread.Sleep(interval * 1000 * 60);
- //Thread.Sleep(10000);
- }
- }
- catch (Exception e)
- {
- logger.LogError("---------" + e.ToString());
- }
- });
- }
- catch (Exception ex)
- {
- var a = ex.Message; //a的值为:发生一个或多个错误。
- var b = ex.GetBaseException(); //b的值为:Task异常测试
- Console.WriteLine(a + "|*|" + b);
- errorinfo = a;
- }
- }
- private void UpdateMachineStatus(string strsql)
- {
- try
- {
- using (IDatabase db = DbFactory.Base("eap"))
- {
- var count = db.ExecuteBySql(strsql);
- }
- }
- catch (Exception ex)
- {
- logger.LogError(ex.ToString()); ;
- }
- }
- public int StartSingHsms(Machine row, IDatabase database)
- {
- List<Telnet> temp = CurrTelnet.Where(c => c.CurrMac.ID == row.ID).ToList();
- if (temp.Count > 0)
- {
- int tempresult = StopSingleHsms(row);
- if (tempresult <= 0)
- return -1;
- }
- string errorinfo = "";
- Telnet hsms = CreateHsms(row, ref errorinfo);// new Hsms03(row);
- int result = hsms.Start(database, ref errorinfo);
- if (result <= 0)
- {
- row.Remark = "启动失败:" + errorinfo;
- return -1;
- }
- row.Remark = "正常";
- CurrTelnet.Add(hsms);
- return 1;
- }
- public Telnet CreateHsms(Machine machine, ref string errorinfo)
- {
- try
- {
- Telnet telnet = new Telnet(machine.IPAddress, 5888, 1000, logger, machine);
- return telnet;
- }
- catch (Exception ex)
- {
- errorinfo = ex.ToString();
- return null;
- }
- }
- public int StopSingleHsms(Machine row)
- {
- try
- {
- string errorinfo = "";
- //先在链表里找,是否已经创建该实例
- List<Telnet> temp = CurrTelnet.Where(a => a.CurrMac.ID == row.ID).ToList();
- if (temp.Count > 0)
- {
- CurrTelnet.Remove(temp[0]);
- }
- row.Remark = "停止";
- return 1;
- }
- catch (Exception ex)
- {
- row.Remark = "启动失败:" + ex.Message.ToString();
- return -1;
- }
- }
- public bool CheckIPFormat(string ip)
- {
- System.Net.IPAddress ipAddress;
- if (System.Net.IPAddress.TryParse(ip, out ipAddress))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- public class Telnet
- {
- private string address;
- private int port;
- private int timeout;
- private static readonly object obj = new object();
- ILogger<AppletStatusCollectionBll> logger;
- public Machine CurrMac = new Machine();//机台数据
- private Thread CheckThread = null;//检查线程
- private Socket CurrSocket = null;
- public Telnet(string Address, int Port, int CommandTimeout, ILogger<AppletStatusCollectionBll> logger, Machine machine)
- {
- address = Address;
- port = Port;
- timeout = CommandTimeout;
- this.logger = logger;
- CurrMac = machine;
- }
- /// <summary>
- /// 启动socket 进行telnet操作
- /// </summary>
- public bool Connect(ref string errorinfo)
- {
- try
- {
- if (CurrSocket == null)
- {
- IPAddress ip = IPAddress.Parse(address);//服务端所在IP
- IPEndPoint ipEnd = new IPEndPoint(ip, port);//服务端所监听的接口
- CurrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- CurrSocket.Connect(ipEnd);
- }
- else
- {
- CurrSocket.Shutdown(SocketShutdown.Both);
- CurrSocket.Close();//关闭Socket
- CurrSocket.Dispose();
- CurrSocket = null;
- IPAddress ip = IPAddress.Parse(address);//服务端所在IP
- IPEndPoint ipEnd = new IPEndPoint(ip, port);//服务端所监听的接口
- CurrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- CurrSocket.Connect(ipEnd);
- }
- return true;
- }
- catch (Exception e)
- {
- errorinfo = e.ToString();
- logger.LogError(errorinfo);
- CurrSocket = null;
- return false;
- }
- }
- public bool ConnectTcp(ref string errorinfo)
- {
- TcpClient tcpClient = null;
- try
- {
- tcpClient = new TcpClient(address, port);
- tcpClient.SendTimeout = timeout;
- return true;
- }
- catch (Exception ex)
- {
- logger.LogError($"TCP检查端口是否连通错误,IP地址:[{address}],错误信息:" + ex.ToString());
- return false;
- }
- finally
- {
- if (tcpClient != null)
- {
- tcpClient.Close();
- tcpClient.Dispose();
- }
- }
- }
- public int Start(IDatabase database, ref string errorinfo)
- {
- StringBuilder sqlstr = new StringBuilder(100);
- int result = StartCheckThread(ref errorinfo);
- if (result <= 0)
- {
- //处理接受失败,写入数据库
- sqlstr.Clear();
- sqlstr.AppendFormat("{0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
- sqlstr.AppendFormat("开始检查线程发生错误\r\n");
- sqlstr.AppendFormat("{0}", errorinfo);
- logger.LogError(sqlstr.ToString());
- return -1;
- }
- return 1;
- }
- public int StartCheckThread(ref string errorinfo)
- {
- try
- {
- //成功后,启动接受线程
- CheckThread = new Thread(CheckThreadFun);
- CheckThread.Start();
- return 1;
- }
- catch (Exception ex)
- {
- errorinfo = ex.Message.ToString();
- return -1;
- }
- }
- private void CheckThreadFun()
- {
- try
- {
- //while (true)
- //{
- string errorinfo = "";
- using (IDatabase db = DbFactory.Base("eap"))
- {
- MachineDal machineDal = new MachineDal(db);
- CurrMac = machineDal.Get(CurrMac.ID);
- var result = Connect(ref errorinfo);
- if (result == true)
- {
- if (CurrMac.AppletS != 1)
- {
- string sql = $"update machine set AppletS=1 where id={CurrMac.ID};";
- logger.LogError(sql);
- db.ExecuteBySql(sql);
- }
- Console.WriteLine(CurrMac.FCode + "已开启小程序");
- logger.LogError(CurrMac.FCode + "已开启小程序");
- }
- else
- {
- if (CurrMac.AppletS != -1)
- {
- string sql = $"update machine set AppletS=-1 where id={CurrMac.ID};";
- logger.LogError(sql);
- db.ExecuteBySql(sql);
- }
- logger.LogError(CurrMac.FCode + "已关闭小程序");
- }
- }
- Thread.Sleep(1000 * 60 * 5);
- //Thread.Sleep(15000);
- //}
- }
- catch (Exception ex)
- {
- logger.LogError(ex.ToString());
- }
- }
- }
- }
|