package ADL400

import (
	"github.com/gogf/gf/v2/errors/gerror"
	"tgk-touch/internal/global"
	"tgk-touch/internal/module/maincontrollerClient"
)

func pushCmd(commUid string, cmd []byte, detail string) ([]byte, error) {

	var result []byte
	err := maincontrollerClient.DeviceCallByDeviceID(commUid, "", "", cmd, &result,
		func(deviceID, method string, params, result interface{}) (deviceType, cmdDetail, cmdDisplay, resultDisplay string) {
			deviceType = "ADL400"
			cmdDetail = detail
			return
		})
	if err != nil {
		return nil, gerror.Wrapf(err, "DeviceCallByDeviceID err ")
	}
	return result, nil
}

func readCmd(commUid string, address byte, startAddr, quantity uint16, detail string) ([]uint16, error) {
	cmd := ReadHoldingRegistersBuilder(address, startAddr, quantity)
	g.Log().Debugf("Modbus 下发 读取命令 = % X", cmd)
	result, err := pushCmd(commUid, cmd, detail)
	if err != nil {
		return nil, gerror.Wrapf(err, "下发[% X]", cmd)
	}
	g.Log().Debugf("Modbus 响应 读取命令 = % X", result)
	r, err := ReadHoldingRegisterParse(result, address, quantity)
	if err != nil {
		return nil, gerror.Wrapf(err, "下发[% X],响应[% X]", cmd, result)
	}
	return r, nil
}

func writeCmd(commUid string, address byte, startAddr uint16, data []uint16, detail string) error {
	writeData, q := WriteMultipleRegistersBuilder(address, startAddr, data)
	g.Log().Debugf("Modbus 下发 写入命令 = % X", writeData)

	result, err := pushCmd(commUid, writeData, detail)
	if err != nil {
		return err
	}
	g.Log().Debugf("Modbus 响应 写入命令 = % X", result)
	err = WriteMultipleRegistersParse(address, startAddr, q, result)
	if err != nil {
		return err
	}
	return nil
}
