package com.youchain.utils;

import com.github.s7connector.api.DaveArea;
import com.github.s7connector.api.S7Connector;
import com.github.s7connector.api.factory.S7ConnectorFactory;
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;


/**
 * S7西门子PLC连接工具类
 *
 * @author <NAME>
 * @date 2024/04/12
 */
@Slf4j
public class S7ConnectorUtils {

    public static S7Connector connect() {
        S7Connector s7Connector = null;
        try {
            s7Connector = S7ConnectorFactory
                    .buildTCPConnector()
                    .withHost("192.168.56.188")//设置PLC的IP地址
                    .withPort(102)//设置PLC的端口号
                    .withTimeout(10000)//设置连接超时时间
                    .withRack(0)//设置PLC的机架号
                    .withSlot(2)//设置PLC的插槽号
                    .build();
            return s7Connector;
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 读取PLC数据
     * 读取条码信息
     *
     * @param connector 连接器
     */
    public static String readMo(S7Connector connector) {
        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, 500, 0);

        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;
    }

    /**
     * 读取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);
        byte[] bytes = buffer.array();
        connector.write(DaveArea.DB, 100, 22, bytes);
        long endTime = System.currentTimeMillis();
        System.out.println((endTime - startTime) + "ms");
        System.out.print("写入成功");
    }

}
