1
#!/usr/bin/env python

from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.payload import BinaryPayloadBuilder
from pymodbus.client.sync import ModbusTcpClient
import struct
import logging

logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.INFO)

ip_address = "192.168.1.55"

client = ModbusTcpClient(ip_address)
if client.connect():    # connection is OK
# write float
#builder = BinaryPayloadBuilder(endian=Endian.Little)
#builder.add_32bit_float(77.77)
#payload = builder.build()
#result  = client.write_registers(1, payload, skip_encode=True)
# read floats
result  = client.read_holding_registers(28, 2)

decoder = BinaryPayloadDecoder.fromRegisters(result.registers, 
endian=Endian.Big)


print  str(decoder.decode_32bit_float())
client.close()
var1 = str(decoder.decode_32bit_float())

I m using PyModbus library to read float values from a PLC . I m getting right value from str(decoder.decode_32bit_float()) but failed to put it into a variable var1. It shows error (in decode 32 bit float return unpack(string, handle)[0] struct.error: unpack requires a string argument of length 4). Thanks in advance

Cheche
  • 1,456
  • 10
  • 27
R-T
  • 113
  • 1
  • 8
  • 2
    ever worked with streams? when you read a stream - f.e. by printing its str(). it is empty afterward because you are past the data in it ... unless more data comes in its empty and can not deliver more. Try `var1 = decoder.decode_32bit_float()` _**first**_ , then `print(var1)` - dont use str unless you need a string. – Patrick Artner Nov 15 '18 at 11:41
  • Thanks Patrick it worked i really appreciate it Thanks – R-T Nov 15 '18 at 11:44
  • Thought so :) maybe delete it before it gets too many downvotes. Its the same for filestreams etc - once you read from it you are past the data you just read. Or selfanswer – Patrick Artner Nov 15 '18 at 11:51
  • @R-T Check this [POST](https://stackoverflow.com/a/53276085/3702377), I hope would help you up – Benyamin Jafari Nov 15 '18 at 22:03

0 Answers0