package com.huimv.admin.jinghongtimer;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.*;
import java.net.Socket;

@Configuration
@EnableScheduling
public class LiaoTaTimer {
    @Scheduled(cron = "0 59 * * * ? ")
    private void readDataFromTcp()   {


    }

    public static void main(String[] args) throws IOException {

        sendHexCommand("000000000006010300000068");
    }


    private static String host = "192.168.2.2";
    private static Integer port =  502;
    private static Integer timeout = 5000;
    public static String sendHexCommand(String hexCommand) throws IOException {
        try (Socket socket = new Socket(host, port)) {
            socket.setSoTimeout(timeout);

            // 发送16进制数据
            OutputStream output = socket.getOutputStream();
            byte[] commandBytes = HexUtils.hexStringToBytes(hexCommand);
            output.write(commandBytes);
            output.flush();

            // 接收响应（需根据协议调整读取逻辑）
            InputStream input = socket.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(temp)) != -1) {
                buffer.write(temp, 0, bytesRead);
                // 根据协议判断是否读取完成（示例：固定长度或结束符）
                if (buffer.size() >= 128) { // 假设预期响应长度128字节
                    break;
                }
            }
            return HexUtils.bytesToHexString(buffer.toByteArray());
        }
    }
}
