You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
3.8 KiB
C#

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* (c) 2026 WenJY
* CLR4.0.30319.42000
* Mr.Wen's MacBook Pro
* Sln.Wcs.Plc
* C46CF1F4-254E-4BA5-B32D-A7175A197EB1
*
* WenJY
*
* 2026-05-06 16:58:24
* V1.0.0
*
*
*--------------------------------------------------------------------
*
*
*
*
* V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using System;
using System.Collections.Generic;
using HslCommunication;
using Microsoft.Extensions.DependencyInjection;
using Sln.Wcs.Model.Domain;
using Sln.Wcs.Plc.Service;
using Sln.Wcs.Plc.Service.Impl;
using Sln.Wcs.Repository.service;
using Sln.Wcs.Serilog;
using SqlSugar;
namespace Sln.Wcs.Plc;
public static class PlcSetUp
{
public static void AddPlcSetup(this IServiceCollection services)
{
//获取 PLC 主机信息=>初始化链接=>将链接信息存入容器中
services.AddSingleton<List<IPlc>>(x =>
{
var _log = x.GetService<SerilogHelper>();
var _hostService = x.GetService<IBaseDeviceHostService>();
List<IPlc> plcs = new List<IPlc>();
try
{
do
{
if (!Authorization.SetAuthorizationCode("3daa5a3b-defd-474d-b2d9-c4d2265dfe20"))
{
_log.Info("HslCommunication激活失败可用时长为24小时");
break;
}
else
{
_log.Info("HslCommunication激活成功");
}
//获取主机信息
List<BaseDeviceHost> deviceHosts = _hostService.Query(x => x.isFlag == 1);
foreach (var item in deviceHosts)
{
IPlc _plc = InitPlc(x, item.hostType);
var conRes = _plc.Connect(item.hostIP, item.hostPort);
if (conRes)
{
_log.Info($"PLC{item.hostIP}:{item.hostPort};连接成功,时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
_plc.ConfigKey = item.hostCode;
plcs.Add(_plc);
}
else
{
_log.Info($"PLC{item.hostIP}:{item.hostPort};连接失败,时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
}
}
} while (false);
}
catch (Exception e)
{
_log.Error($"PLC初始化连接异常{e.Message}");
}
return plcs;
});
}
private static IPlc InitPlc(IServiceProvider serviceProvider, int plcType)
{
IPlc _plc = null;
var _inovance = serviceProvider.GetRequiredService<InovanceImpl>();
var _siemens = serviceProvider.GetRequiredService<SiemensImpl>();
switch (plcType)
{
case 0:
_plc = _siemens;
break;
case 1:
_plc = _inovance;
break;
// case "MelsecBinaryPlc":
// _plc = _melsecBinary;
// break;
// case "OmronNJPlc":
// _plc = _omronNj;
// break;
default:
break;
}
return _plc;
}
}