在使用python-lib minimalmodbus时,如何更改解释响应的字节顺序?

2024-09-29 22:18:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python库“minimamodbus”与modbus设备通信:

import minimalmodbus
from minimalmodbus import Instrument

minimalmodbus.BAUDRATE = 9600
m = Instrument('com2', 1)
m.debug=True
print m.read_long(4156)

结果是:

^{pr2}$

响应数据为65536,十六进制为0x00010000。但我已经知道数据应该是十六进制的。原因很明显:minimamodbus将响应数据'\x00\x01\x00\x00'解释为0x00010000,而对于我的modbus设备,应该是0x00000001。我已经参考了文档(http://minimalmodbus.sourceforge.net/#known-issues),在那里我看到了这一点:

For the data types involving more than one register (float, long etc), there are differences in the byte order used by different manufacturers. A floating point value of 1.0 is encoded (in single precision) as 3f800000 (hex). In this implementation the data will be sent as '\x3f\x80' and '\x00\x00' to two consecutive registers. Make sure to test that it makes sense for your instrument. It is pretty straight-forward to change this code if some other byte order is required by anyone (see support section).

我想问:有没有人遇到过同样的问题,并找到了一个简单而快速的方法(正如作者所说)来改变minimamodbus的默认字节顺序?在

编辑: 我找到了解决这个问题的方法,但我不知道这是否是最简单的:

  def _performCommand(self, functioncode, payloadToSlave):
        '''
        reimplement the _performCommand function in subclass of minimalmodbus.Instrument
        '''          
        payloadFromSlave = Instrument._performCommand(self, functioncode, payloadToSlave)

        if functioncode in [3, 4]:
            #reorder data in response while reading multiple registers
            return payloadFromSlave[0] + self._restructure(payloadFromSlave)
        else:
            return payloadFromSlave

    def _restructure(self, byteCode):
        '''
       reorder byte code for my device, e.g.:
       '\x00\x01\x00\x02'  --->'\x00\x02\x00\x01'
       (byte order may differ for different manufacturers,refer to  http://www.simplymodbus.ca/FAQ.htm#Order)
        '''
        newByteCode = ''
        for i in range(len(byteCode)-2, -1, -2):
            newByteCode += byteCode[i:i+2]
        return newByteCode

Tags: theto数据inselffordataorder

热门问题