Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在使用python库时,如何更改解释响应的字节顺序?_Python_Modbus - Fatal编程技术网

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

在使用python库时,如何更改解释响应的字节顺序?,python,modbus,Python,Modbus,我使用python库“minimalmodbus”与modbus设备通信: import minimalmodbus from minimalmodbus import Instrument minimalmodbus.BAUDRATE = 9600 m = Instrument('com2', 1) m.debug=True print m.read_long(4156) 结果是: MinimalModbus debug mode. Writing to instrument (expec

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

import minimalmodbus
from minimalmodbus import Instrument

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

MinimalModbus debug mode. Writing to instrument (expecting 9 bytes back): '\x01\x03\x10<\x00\x02\x00\xc7'
MinimalModbus debug mode. No sleep required before write. Time since previous read: 1422431606124.0 ms, minimum silent period: 4.01 ms.
MinimalModbus debug mode. Response from instrument: '\x01\x03\x04\x00\x01\x00\x00\xab\xf3' (9 bytes), roundtrip time: 28.0 ms. Timeout setting: 50.0 ms.
65536

这里提到了一个变通方法:文档中的变通方法对我没有帮助。但你的解决办法完全奏效了。谢谢
  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