package com.youchain.utils;

import cn.hutool.core.date.DateUtil;
import com.github.s7connector.api.DaveArea;
import com.github.s7connector.api.S7Connector;
import com.github.s7connector.api.S7Serializer;
import com.github.s7connector.api.factory.S7ConnectorFactory;
import com.github.s7connector.api.factory.S7SerializerFactory;
import com.github.s7connector.impl.serializer.converter.StringConverter;
import com.sun.mail.iap.ConnectionException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;


/**
 * S7西门子PLC连接工具类
 *
 * @author <NAME>
 * @date 2024/04/12
 */
@Slf4j
public class S7ConnectorUtils {
    public static S7Connector s7Connector=null;
    public static S7Connector connect() {
        if (s7Connector != null){
            try {
                s7Connector.close();
                //关闭连接
//                log.info("关闭s7连接");
            }catch (Exception e){

            }finally {
                s7Connector=null;
            }
        }
        s7Connector = S7ConnectorFactory
                .buildTCPConnector()
                .withHost(BaseCode.PLC_IP)//设置PLC的IP地址
//                    .withPort(BaseCode.PLC_PORT)//设置PLC的端口号
                .withTimeout(10000) //连接超时时间
                .withRack(0)//设置PLC的机架号
                .withSlot(1)//设置PLC的插槽号
                .build();
        S7Serializer s7Serializer2L = S7SerializerFactory.buildSerializer(s7Connector);
//        log.info("初始化s7连接");
        return s7Connector;
    }
    public static void main(String[] args) {
        /*String a="LB]A0006907]240522]12125300001741]50.00]240522554318]]";
        String I=a.substring(19, 33);
        System.out.println("I:"+I);
        String M=a.substring(40, 52);
        System.out.println("M:"+M);*/
        S7ConnectorUtils.connect();
        String lh = S7ConnectorUtils.readMo(s7Connector,0);
        System.out.println("LH:"+lh);
        String mo = S7ConnectorUtils.readMo(s7Connector,12);
        System.out.println("MO:"+mo);
//        S7ConnectorUtils.write(s7Connector,1);

        /*if (lh.length()>0&&mo.length()>0){
            S7ConnectorUtils.write(s7Connector,1);
        }*/
       /* String a = cn.hutool.core.date.DateUtil.format(DateUtil.beginOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
        System.out.println("日期："+a);*/
    }

    /**
     * 读取PLC数据
     * 读取条码信息
     * @param offset 偏移量 0-箱号，12-MO票
     * @param connector 连接器
     */
    public static String readMo(S7Connector connector,int offset) {
        String mo = null;
        if (connector == null) {
            throw new RuntimeException("PLC连接失败，请检查!");
        }
        long startTime = System.currentTimeMillis();
        /**
         * 读取数据
         * 选择区块：DB
         * 区块编号：100
         * 字节：500
         * 偏移：0
         */
        byte[] PlcData = connector.read(DaveArea.DB, 100, 60, offset);

        long endTime = System.currentTimeMillis();
//        log.info("读取耗时:" + (endTime - startTime) + "ms");

        String str1 = "";
        StringConverter converter = new StringConverter();

        mo = converter.extract(str1.getClass(), PlcData, 0, 0);
        log.info("内置方法转换str=" + mo);
        /*try {
            connector.close();
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        return mo.replace(" ", "");
    }

    /**
     * 读取PLC数据
     * 读取容器信息
     *
     * @param connector 连接器
     */
    public static Integer readStock(S7Connector connector) throws IOException {
        Integer status = null;
        try {

            if (connector == null) {
                throw new IllegalArgumentException("PLC连接失败，请检查!");
            }
            long startTime = System.currentTimeMillis();
            /**
             * 读取数据
             * 选择区块：DB
             * 区块编号：100
             * 字节：1
             * 偏移：0
             */
            byte[] PlcData = connector.read(DaveArea.DB, 100, 1, 24);

            long endTime = System.currentTimeMillis();
            log.info("读取耗时:" + (endTime - startTime) + "ms");

            Integer stock = null;
            StringConverter converter = new StringConverter();

            status = converter.extract(stock.getClass(), PlcData, 0, 0);
        } catch (Exception e) {
            throw new IOException("读取PLC数据异常", e);
        } finally {
            connector.close();
        }
        return status;
    }

    /**
     * 写入数据到PLC
     *
     * @param connector 连接器
     * @param instruct  写入的数据;上位机给PLC发扫码合格指令，不合格写1，合格写2，0无效，上位机写，PLC清
     */
    public static void write(S7Connector connector, Integer instruct) {
        long startTime = System.currentTimeMillis();
        ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
        buffer.putInt(instruct);
        System.out.println("写入日志:instruct"+instruct);
        byte[] bytes = buffer.array();
        connector.write(DaveArea.DB, 100, 70, bytes);
        long endTime = System.currentTimeMillis();
        System.out.println((endTime - startTime) + "ms");
    }

}
