package com.yfd.platform.modules.robotcomand.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 *
 * @Date: 2023/9/21 16:32
 * @Description:
 */
@Service
@Slf4j
public class RobotUdpService {

    private boolean online = false;

    // 每隔0.5秒发送心跳
    //@Scheduled(fixedRate = 500)
    public void sendHeartbeat() {
        String heartbeatCommand = "33";
        String response = this.sendAndReceive(heartbeatCommand);
        // 处理机器人的响应，检查机器人是否在线
        // 处理机器人下线的情况
        online = "1".equals(response);
    }


    /**********************************
     * 用途说明: 发送机器人指令
     * 参数说明 command
     * 返回值说明: java.lang.String
     ***********************************/
    public String sendSimple(String command) {
        if (!online) {
            return "机器人不在线";
        }
        return sendAndReceive(command);
    }

    /**********************************
     * 用途说明: 退出机器人
     * 参数说明 command
     * 返回值说明: java.lang.String
     ***********************************/
    public String exitRobotSession(String command) {
        return sendAndReceive(command);
    }

    /**********************************
    * 用途说明: 发送指令
    * 参数说明 command
    * 返回值说明: java.lang.String
    ***********************************/
    public String sendAndReceive(String command) {
        try {
            DatagramSocket socket = new DatagramSocket();

            // 机器人的IP地址和端口号
            InetAddress robotAddress = InetAddress.getByName("192.168.1.120");
            // 机器人的实际端口号
            int robotPort = 43893;

            // 发送数据给机器人
            byte[] sendData = command.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, robotAddress, robotPort);
            socket.send(sendPacket);

            // 接收机器人的响应
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);

            // 处理机器人的响应数据
            String response = new String(receivePacket.getData(), 0, receivePacket.getLength());

            // 关闭Socket
            socket.close();

            return response;
        } catch (Exception e) {
            log.error(e.getMessage());;
            return "通信失败";
        }
    }

}
