package com.chinaitop.depot.intelligent.socket;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

@Component
@SuppressWarnings("all")
public class SocketClient {

    @Value("${socket-url}")
    private String host;
    @Value("${socket-port}")
    private int port;

    /**
     * 0：失败；1：成功；2：设备通讯异常；3：设备故障；4：未知原因; 5: 本地模式(有的设备有本地模式，即无法远程控制)
     *
     * @param bytes
     * @return
     */
    public String startClient(byte[] bytes) {
        Socket socket = null;
        DataOutputStream dos = null;
        DataInputStream dis = null;
        String format = "";
        String result = "";
        try {
            //与服务端建立连接
            socket = new Socket(host, port);
            if (socket.isConnected()) {
                // 向服务端程序发送数据
                dos = new DataOutputStream(socket.getOutputStream());
                // 发送bype[]数组类型的
                dos.write(bytes);
                // 从服务端程序接收数据
                dis = new DataInputStream(socket.getInputStream());
                for (int i = 0; i < 7; i++) {
                    int read = dis.read();
                    format = String.format("%02x", read).toUpperCase();
                    result += format;
                }
            } else {
                return "建立连接失败";
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return "本地调用异常";
        } finally {
            try {
                socket.close();
                dos.close();
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
                return "关闭服务失败";
            }
        }
    }

}