package main

import (
	"cicv-data-closedloop/common/util"
	"fmt"
	"github.com/bluenviron/goroslib/v2"
	"github.com/bluenviron/goroslib/v2/pkg/msg"
	"os"
	"sync"
	"time"
)

type HeartBeatInfo struct {
	msg.Package `ros:"diag_msgs"`
	ModuleName  string  `rosname:"module_name"`
	Rate        int8    `rosname:"rate"`
	Timestamp   float64 `rosname:"timestamp"`
}

var lastTime time.Time
var mutex sync.Mutex
var sub *goroslib.Subscriber

func main() {
	lastTime = time.Now()

	// 1 启动 shell 脚本 dpi_start.sh
	_, s, err := util.ExecuteWithDirSync("/data", "sh", "dpi_start.sh")
	if err != nil {
		fmt.Println("执行启动命令报错，执行结果为：", s, "，错误信息为：", err)
		os.Exit(1)
	}
	fmt.Println("执行启动命令 sh dpi_start.sh 成功，执行结果为：", s)

	time.Sleep(5 * time.Second)
	// 2 监听 ros 话题 /heartbeat_info
	rosNode, _ := goroslib.NewNode(goroslib.NodeConf{
		Name:          "dpi_with_heartbeatInfo",
		MasterAddress: "127.0.0.1:11311",
	})
	sub, err = goroslib.NewSubscriber(goroslib.SubscriberConf{
		Node:  rosNode,
		Topic: "/heartbeat_info",
		Callback: func(data *HeartBeatInfo) {
			fmt.Println("监听到数据：", data)
			lastTime = time.Now()
		}})
	if err != nil {
		fmt.Println("监听话题/heartbeat_info报错", err)
		os.Exit(1)
	}
	// 3 超过5秒没有接收到数据则执行 dpi_stop.sh 和 dpi_start.sh

	for {
		time.Sleep(1 * time.Second)
		if time.Since(lastTime).Seconds() > 5.00 {
			fmt.Println("超过5秒没有监听到/heartbeat_info数据，即将重启dpi。")
			_, s, err := util.ExecuteWithDirSync("/data", "sh", "dpi_stop.sh")
			if err != nil {
				fmt.Println("执行停止命令报错，执行结果为：", s, "，错误信息为：", err)
				continue
			}
			fmt.Println("执行停止命令 sh dpi_stop.sh 成功，执行结果为：", s)
			sub.Close()

			_, s, err = util.ExecuteWithDirSync("/data", "sh", "dpi_start.sh")
			if err != nil {
				fmt.Println("执行启动命令报错，执行结果为：", s, "，错误信息为：", err)
				continue
			}
			fmt.Println("执行启动命令 sh dpi_start.sh 成功，执行结果为：", s)
			time.Sleep(5 * time.Second)
			sub, err = goroslib.NewSubscriber(goroslib.SubscriberConf{
				Node:  rosNode,
				Topic: "/heartbeat_info",
				Callback: func(data *HeartBeatInfo) {
					fmt.Println("监听到数据：", data)
					lastTime = time.Now()
				}})
			if err != nil {
				fmt.Println("监听话题/heartbeat_info报错", err)
				os.Exit(1)
			}
			lastTime = time.Now()
		}
	}

}
