package m9z

import (
	"fmt"
)

// 读取设备输出状态参数
type OutStatus struct {
	BackupByte2 byte   `json:"backup_byte1"` //备用字节下标2
	Loops       []Loop `json:"loops"`        //回路数据
}

func DeviceOutStatusRead(deviceId string) (*OutStatus, error) {
	out := &OutStatus{}
	readResp, err := ReadCmd(deviceId, deviceOutStatus, "读取设备输出状态参数")
	if err != nil {
		return nil, err
	}

	// 解析10路的继电器动作状态
	relayBits := BytesToUint16LE(readResp.Data[0:2])
	//log.Printf("继电器状态（二进制）: %016b,% X", relayBits, readResp.Data[0:2]) // 补零显示16位
	loops := make([]Loop, 10)
	for i := 0; i < 10; i++ {
		var loop Loop
		bit := (relayBits >> i) & 0x01 // 取第i位的值
		loop.IsOpen = bit == 1
		loop.Index = i
		loop.Name = fmt.Sprintf("#%+v", i+1)
		loops[i] = loop
	}
	out.BackupByte2 = readResp.Data[2]
	pwms := readResp.Data[3 : len(readResp.Data)-1]
	for index, pwm := range pwms {
		loops[index].Pwm = hexToPercent(pwm)
	}
	out.Loops = loops
	return out, err
}
