using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using LeatherApp.Utils;
using Models;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using S7.Net;
namespace LeatherApp.Device
{
///
/// PLC操作类
///
public class PLCDev : IDisposable
{
private Plc devPlc;
public Action WarningEvent;
///
/// 运行状态
///
public Action RuningStateChangeEvent;
///
/// 是否打开设备成功
///
public bool IsInit { get; private set; } = false;
private Thread t_task1;
public bool? devRunningState { get; private set; }
public PLCDev()
{
}
public bool start(CpuType cpu, string iPAdrees, short rack, short slot)
{
try
{
devPlc = new Plc(cpu, iPAdrees, rack, slot);
devPlc.Open();
if (!devPlc.IsConnected) throw new Exception("Plc连接失败!");
IsInit = true;
t_task1 = new System.Threading.Thread(run1);
t_task1.IsBackground = true;
t_task1.Start();
return true;
}
catch (Exception ex)
{
WarningEvent?.BeginInvoke(DateTime.Now,WarningEnum.High, ex.Message,null,null);
return false;
}
}
public void stop()
{
if (!IsInit) return;
try
{
IsInit = false;
//timer.Elapsed -= Timer_Elapsed;
if (t_task1 != null)
{
bool b = t_task1.Join(1000);
if (!b) t_task1.Abort();
t_task1 = null;
}
devPlc.Close();
}
catch { }
}
private void run1()
{
while (IsInit)
{
//1.3
bool res = (Boolean)devPlc.Read("DB3.DBX1.3");
if (devRunningState == null || devRunningState != res)
{
devRunningState = res;
RuningStateChangeEvent?.Invoke(res);
}
Thread.Sleep(100);
}
}
///
/// 启动DEV
///
public void runDev()
{
if (IsInit)
{
devPlc.Write("DB3.DBX0.1", false);
devPlc.Write("DB3.DBX0.0", true);//启动
}
}
///
/// 停止DEV
///
public void pauseDev()
{
if (IsInit)
{
devPlc.Write("DB3.DBX0.0", false);
devPlc.Write("DB3.DBX0.1", true);//停止
}
}
//private void callback(PhotoTask task)
//{
// //返回成功/失败,异步调用
// if (task.finishEvent != null || (task.finishEvent = finishEvent) != null)
// //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null);
// System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task);
//}
////异步回调
//WaitCallback waitCallback = new WaitCallback(o =>
//{
// var task = (PhotoTask)o;
// task.finishEvent(task);
//});
public void Dispose()
{
stop();
}
}
}