package m9z

// 时间获取
import (
	"encoding/binary"
	"fmt"
	"log"
	"time"
)

func DeviceTimeRead(deviceId string) (time.Time, int64, error) {
	readResp, err := ReadCmd(deviceId, deviceTime, "读取日期时间")
	if err != nil {
		return time.Time{}, 0, err
	}
	u := binary.LittleEndian.Uint32(readResp.Data)
	return time.Unix(int64(u), 0), int64(u), nil
}

// DeviceTimeWrite 将当前时间写入设备
func DeviceTimeWrite(deviceId string, t time.Time) error {

	// 2. 将时间转换为Unix时间戳（秒）
	unixTime := uint32(t.Unix())

	// 3. 准备写入数据（小端序4字节）
	timeData := make([]byte, 4)
	binary.LittleEndian.PutUint32(timeData, unixTime)

	// 5. 发送命令
	writeResp, err := WriteCmd(deviceId, deviceTime, timeData, "将当前时间写入设备")
	if err != nil {
		return err
	}

	// 6. 验证响应
	if !writeResp.Success {
		return fmt.Errorf("设备返回写入失败  ")
	}

	log.Printf("成功写入设备时间: %s", t.Format("2006-01-02 15:04:05"))
	return nil
}
