using HslCommunication;
using HslCommunication.Profinet.Melsec;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SLZ_4
{
    public class PlcObject
    {        
        public MelsecFxSerial PLC;  //串口通行方式：三菱FX3U

        /*******耕得柜式离线式上位机点位***********/
        //M600:CH1；M601:CH2；true:开启扫码；false:关闭扫码
        //D120:CH1；D121:CH2；10扫码完成
        /*******耕得柜式离线式上位机点位***********/

        /*******华贝上位机点位***********/
        //读实时下压力：D105:CH1；D107:CH2
        //写：
        //M600:CH1；M601:CH2；true:开启扫码；false:关闭扫码
        //D500:CH1；D501:CH2；10扫码完成
        //M602:CH1；M603:CH2；true:负压模式；false:正压模式
        /*******耕得柜式离线式上位机点位***********/

        /*******航同离线式上位机点位***********/
        //M600:CH1；M601:CH2；true:开启扫码；false:关闭扫码
        //D530:CH1；D531:CH2；10扫码完成
        /*******航同离线式上位机点位***********/
        public PlcObject()
        {
            PLC = new MelsecFxSerial();
        }

        public void openPLC(PLC_PARAM plcParam)
        {
            try
            {
                PLC.SerialPortInni(sp =>
                {
                    sp.PortName = plcParam.sPort;
                    sp.BaudRate = plcParam.iBaudrate;
                    sp.DataBits = 7;
                    sp.StopBits = System.IO.Ports.StopBits.One;
                    sp.Parity = System.IO.Ports.Parity.Even;
                });
                PLC.Open();
            }
            catch (Exception ex)
            {
                FileLogger.Log("打开PLC失败:" + ex.Message, LogLevel.ERROR);
            }
        }
        public void closePLC()
        {
            PLC.Close();
        }

        public bool SetScan(int iCH, bool bStart)
        {
            bool bRet = false;
            if (PLC.IsOpen())
            {
                bRet = PLC.Write(iCH == 0 ? "M600" : "M601", bStart).IsSuccess;
            }
            return bRet;
        }

        public bool ScanFinish(int iCH)
        {
            bool bRet = false;
            if (PLC.IsOpen())
            {
                bRet = PLC.Write(iCH == 0 ? "D530" : "D531", 10).IsSuccess;
            }
            return bRet;
        }
    }
}
