using System;
|
using System.Collections.Generic;
|
using System.ComponentModel;
|
using System.Linq;
|
using System.Threading;
|
using System.Windows.Forms;
|
using AxActUtlTypeLib;
|
using HH.WCS.Mobox3.RiDong.util;
|
|
public static class MitsubishiHelper
|
{
|
private static Dictionary<string, AxActUtlType> plcDic = new Dictionary<string, AxActUtlType>();
|
private static Form form = new Form(); // 创建一个隐藏的窗体
|
|
static MitsubishiHelper()
|
{
|
// 确保窗体已创建并运行消息泵
|
var thread = new Thread(() => Application.Run(form));
|
thread.SetApartmentState(ApartmentState.STA); // 设置线程为 STA
|
thread.Start();
|
|
// 在静态构造函数中调用 Init 方法
|
var linePlcInfoDtos = Settings.LinePlcInfos.Where(p => p.enable == 1).ToList();
|
if (linePlcInfoDtos.Any())
|
{
|
foreach (var item in linePlcInfoDtos)
|
{
|
Init(item.address);
|
}
|
}
|
}
|
|
public static int GetDevice(string ip, string szDeviceName)
|
{
|
int result = -1;
|
var thread = new Thread(() =>
|
{
|
try
|
{
|
if (plcDic.ContainsKey(ip))
|
{
|
plcDic[ip].Open();
|
int deviceValue;
|
var iReturnCode = plcDic[ip].GetDevice(szDeviceName, out deviceValue);
|
if (iReturnCode == 0)
|
{
|
result = deviceValue;
|
}
|
else
|
{
|
plcDic[ip].Close();
|
plcDic[ip].Open();
|
}
|
}
|
}
|
catch (Exception ex)
|
{
|
Console.WriteLine("Error in STA thread: " + ex.Message);
|
}
|
});
|
|
thread.SetApartmentState(ApartmentState.STA); // 设置线程为 STA
|
thread.Start();
|
thread.Join(); // 等待线程完成
|
|
return result;
|
}
|
|
public static bool SetDevice(string ip, string szDeviceName, int arrDeviceValue)
|
{
|
bool result = false;
|
var thread = new Thread(() =>
|
{
|
try
|
{
|
if (plcDic.ContainsKey(ip))
|
{
|
plcDic[ip].Open();
|
var iReturnCode = plcDic[ip].SetDevice(szDeviceName, arrDeviceValue);
|
if (iReturnCode == 0)
|
{
|
result = true;
|
}
|
else
|
{
|
plcDic[ip].Close();
|
plcDic[ip].Open();
|
}
|
}
|
}
|
catch (Exception ex)
|
{
|
Console.WriteLine("Error in STA thread: " + ex.Message);
|
}
|
});
|
|
thread.SetApartmentState(ApartmentState.STA); // 设置线程为 STA
|
thread.Start();
|
thread.Join(); // 等待线程完成
|
|
return result;
|
}
|
|
private static void Init(string ip)
|
{
|
var thread = new Thread(() =>
|
{
|
try
|
{
|
if (!plcDic.ContainsKey(ip))
|
{
|
var axActUtlType = new AxActUtlType();
|
((ISupportInitialize)axActUtlType).BeginInit();
|
form.Controls.Add(axActUtlType); // 将控件添加到窗体中
|
((ISupportInitialize)axActUtlType).EndInit();
|
axActUtlType.ActLogicalStationNumber = 1; // 设置逻辑站号
|
var res = axActUtlType.Open();
|
if (res == 0)
|
{
|
plcDic.Add(ip, axActUtlType);
|
}
|
}
|
}
|
catch (Exception ex)
|
{
|
Console.WriteLine("Error in STA thread: " + ex.Message);
|
}
|
});
|
|
thread.SetApartmentState(ApartmentState.STA); // 设置线程为 STA
|
thread.Start();
|
thread.Join(); // 等待线程完成
|
}
|
}
|