pycom / pycom-modbus

45 stars 44 forks source link

No way for reading float values #7

Open luixal opened 4 years ago

luixal commented 4 years ago

Hi,

I'm reading values from a sensor that uses RS485 and sends inverse float values with function code 4 (addresses 0, 2 and 4) and it was imposible for me to read those values using the read_input_registers function (which uses function code 4).

I had to add another function for converting values to float instead of short (quite hardcoded for my case, not so much into modbus):

def _to_float(self, byte_array, signed=True):
        # response_quantity = int(len(byte_array) / 2)
        # this always returned 2
        # fmt = '>' + ('f' * response_quantity)
        # so fmt ended up like '>ff' and caused a buffer issue, so I hardcoded it to ' >f'
        # also, no idea about signed floats, just left the signed var to be consistent
        return struct.unpack('>f', byte_array)

and a new function copy&pasted from read_input_registers, but using the_to_float` function defined above:

def read_float_registers(self, slave_addr, starting_address, register_quantity, signed=True):
        modbus_pdu = functions.read_input_registers(starting_address, register_quantity)

        resp_data = self._send_receive(modbus_pdu, slave_addr, True)
        register_value = self._to_float(resp_data, signed)

        return register_value

Any cleaner/correct/good way to implement this?