import struct

def reorderBytes(byteStream, format):
    if format == 'ABCD':
        return byteStream[::-1]
    elif format == 'DCBA':
        return byteStream
    elif format == 'BADC':
        return bytes([byteStream[2], byteStream[3], byteStream[0], byteStream[1]])
    elif format == 'CDAB':
        return bytes([byteStream[1], byteStream[0], byteStream[3], byteStream[2]])
    else:
        raise ValueError("Invalid format")

# 大端模式
def floatToABCD(value):
	valueByte = struct.unpack('>HH',struct.pack('>f', value))
	return valueByte

# 小端模式
def floatToDCBA(value):
	valueByte = struct.unpack('>HH', struct.pack('<f', value))
	return valueByte

# 单字反转
def floatToBADC(value):
	valueByte = struct.unpack('<HH', struct.pack('>f', value))
	return valueByte

#  双字反转
def floatToCDAB(value):
	valueByte = struct.unpack('<HH', struct.pack('<f', value))
	return valueByte


def ABCDToFloat(value):
	valueByte = struct.unpack('>f',struct.pack('>HH', value[0], value[1])) 
	return valueByte[0]

# 小端模式
def DCBAToFloat(value):
	valueByte = struct.unpack('<f', struct.pack('>HH', value[0], value[1])) 
	return valueByte[0]

def BADCToFloat(value):
	valueByte = struct.unpack('>f', struct.pack('<HH', value[0], value[1])) 
	return valueByte[0]


def CDABToFloat(value):
	valueByte = struct.unpack('<f', struct.pack('<HH', value[0], value[1]))
	return valueByte[0]

def bytesTOFloat(value, order):
	match order:
		case 'ABCD':
			return ABCDToFloat(value)
		case 'DCBA':
			return DCBAToFloat(value)
		case 'CDAB':
			return CDABToFloat(value)
		case 'BADC':
			return BADCToFloat(value)


def floatToBytes(values, length, order):
	# 判断order是否为ABCD或BADC
	# order = '>' if order in ['ABCD', 'BADC'] else '<'
	# hOrder = '<'if order.byte in ['ABCD', 'DCBA'] else '>'
	# 获取values的长度
	valuesNums = len(values)
	# print(values,valuesNums,6666)
	# 将values转换为字节流
	valueByte = struct.pack(f"!{'f' * valuesNums}", *values)
	valueByte = reorderBytes(valueByte, format = order) + struct.pack('B' * (length - valuesNums * 4), *[0] * (length - valuesNums * 4))
# {'B' * (length - 4 * valuesNums) *[0] * (length - 4 * valuesNums)
	# print(valueByte)
	# 返回转换后的字节流
	return valueByte

def coilsToBytes(values, length):
	decimalNumbers = []
	binaryNumber = ''.join([str(x) for x in list(reversed(values))])
	zeroNeeded = 0 if len(binaryNumber) % 8 == 0 else 8 - (len(binaryNumber) % 8)
	binaryNumber = '0' * zeroNeeded + binaryNumber
	for i in range(0, len(binaryNumber), 8):
		eightValues = binaryNumber[i:i+8]
		decimalNumbers.append(int(eightValues, 2))
	valueByte = struct.pack("B" * length, *decimalNumbers, *[0] * (length - len(decimalNumbers)))
	return valueByte

def bytesToCoils(valueByte):
    binaryNumber = ''.join([format(x, '08b') for x in valueByte])
    values = list(reversed([int(x) for x in binaryNumber]))
    # print(values)
    return values



