本文整理汇总了Python中pymodbus.payload.BinaryPayloadDecoder类的典型用法代码示例。如果您正苦于以下问题:Python BinaryPayloadDecoder类的具体用法?Python BinaryPayloadDecoder怎么用?Python BinaryPayloadDecoder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BinaryPayloadDecoder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setValues
def setValues(self, address, values):
''' Sets the requested values of the datastore
:param address: The starting address
:param values: The new values to be set
'''
if not isinstance(values, list):
values = [values]
start = address - self.address
self.values[start:start + len(values)] = values
if start <= 550 < start + len(values):
if self.values[500] != values[550-start]:
logInfo.debug("ModbusMySequentialDataBlock.setValues updating 500({0}) with new value {1}".format(self.values[500],values[550-start]))
self.values[500] = values[550-start]
if start <= 552 < start + len(values):
global g_Time
global s_Time
decoder = BinaryPayloadDecoder.fromRegisters(self.values[502:503],endian=Endian.Little)
bits_502 = decoder.decode_bits()
bits_502 += decoder.decode_bits()
decoder = BinaryPayloadDecoder.fromRegisters(self.values[506:507],endian=Endian.Little)
bits_506 = decoder.decode_bits()
bits_506 += decoder.decode_bits()
decoder = BinaryPayloadDecoder.fromRegisters(values[552-start:553-start],endian=Endian.Little)
bits_552 = decoder.decode_bits()
bits_552 += decoder.decode_bits()
logInfo.debug("ModbusMySequentialDataBlock.setValues updating 552({0}) {1}".format(values[552-start], bits_552))
if bits_552[2]:
print "ModbusMySequentialDataBlock.setValues start iniettore da remoto"
logInfo.debug("ModbusMySequentialDataBlock.setValues start iniettore da remoto")
g_Time = 0
bits_502[7] = 1 # START INIETTORE
self.hndlr.pumpStarted = True
bits_506[2] = 1
bits_506[3] = 0
bits_552[2] = 0
bits_builder = BinaryPayloadBuilder(endian=Endian.Little)
bits_builder.add_bits(bits_502)
bits_builder.add_bits(bits_506)
bits_builder.add_bits(bits_552)
bits_reg = bits_builder.to_registers()
self.values[502:503]=[bits_reg[0]]
self.values[506:507]=[bits_reg[1]]
self.values[552:553]=[bits_reg[2]]
if bits_552[3]:
print "ModbusMySequentialDataBlock.setValues stop iniettore da remoto"
logInfo.debug("ModbusMySequentialDataBlock.setValues stop iniettore da remoto")
bits_502[7] = 0 # STOP INIETTORE
bits_506[2] = 0
self.hndlr.pumpStarted = False
bits_506[3] = 1
bits_552[3] = 0
bits_builder = BinaryPayloadBuilder(endian=Endian.Little)
bits_builder.add_bits(bits_502)
bits_builder.add_bits(bits_506)
bits_builder.add_bits(bits_552)
bits_reg=bits_builder.to_registers()
self.values[502:503]=[bits_reg[0]]
self.values[506:507]=[bits_reg[1]]
self.values[552:553]=[bits_reg[2]]
示例2: testPayloadDecoderReset
def testPayloadDecoderReset(self):
""" Test the payload decoder reset functionality """
decoder = BinaryPayloadDecoder(b'\x12\x34')
self.assertEqual(0x12, decoder.decode_8bit_uint())
self.assertEqual(0x34, decoder.decode_8bit_uint())
decoder.reset()
self.assertEqual(0x3412, decoder.decode_16bit_uint())
示例3: __init__
def __init__(self, payload, byteorder):
""" Initialize a new instance of the SunspecDecoder
.. note:: This is always set to big endian byte order
as specified in the protocol.
"""
byteorder = Endian.Big
BinaryPayloadDecoder.__init__(self, payload, byteorder)
示例4: checkPump
def checkPump(self,client_p):
rr = client_p.read_holding_registers(500,100,unit=1)
# conversione in bit array da 552
decoder = BinaryPayloadDecoder.fromRegisters(rr.registers[52:53],endian=Endian.Little)
bits_552 = decoder.decode_bits()
bits_552 += decoder.decode_bits()
bits_552[10] = True
b_builder = BinaryPayloadBuilder(endian=Endian.Little)
b_builder.add_bits(bits_552)
reg_552 = b_builder.to_registers()
rr.registers[52:53] = reg_552
for it in range(10):
self.p_count += 1
rr.registers[50] = self.p_count
rq = client_p.write_registers(500, rr.registers,unit=1)
if rq.function_code < 0x80:
rr_p = client_p.read_holding_registers(500,100,unit=1)
if len(rr_p.registers)==100 and rr_p.registers[0]==self.p_count:
decoder = BinaryPayloadDecoder.fromRegisters(rr_p.registers[2:7],endian=Endian.Little)
# 502
bits_502 = decoder.decode_bits()
bits_502 += decoder.decode_bits()
# 503
bits_503 = decoder.decode_bits()
bits_503 += decoder.decode_bits()
# 504
bits_504 = decoder.decode_bits()
bits_504 += decoder.decode_bits()
# 505
bits_505 = decoder.decode_bits()
bits_505 += decoder.decode_bits()
# 506
bits_506 = decoder.decode_bits()
bits_506 += decoder.decode_bits()
if bits_502[7]:
builder.get_object("switchPumpStatus").set_active(True)
else:
builder.get_object("switchPumpStatus").set_active(False)
if bits_502[4] == False and bits_502[10] == True:
builder.get_object("switchPumpStatus").set_sensitive(True)
else:
builder.get_object("switchPumpStatus").set_sensitive(False)
else:
print "errore checkPump %d" % self.p_count
bits_552[10] = False
print str(bits_552)
b_builder = BinaryPayloadBuilder(endian=Endian.Little)
b_builder.add_bits(bits_552)
reg_552_2 = b_builder.to_registers()
rr.registers[52:53] = reg_552_2
rq = client_p.write_registers(500, rr.registers,unit=1)
if rq.function_code < 0x80:
pass
else:
print "checkPump terminato con scrittura KO"
示例5: on_switchPumpStatus_state_set
def on_switchPumpStatus_state_set(self, switch,gparam):
self.ret_p=self.client_p.connect()
rr = self.client_p.read_holding_registers(500,100,unit=1)
# conversione in bit array da 552
decoder = BinaryPayloadDecoder.fromRegisters(rr.registers[52:53],endian=Endian.Little)
bits_552 = decoder.decode_bits()
bits_552 += decoder.decode_bits()
decoder = BinaryPayloadDecoder.fromRegisters(rr.registers[2:7],endian=Endian.Little)
# 502
bits_502 = decoder.decode_bits()
bits_502 += decoder.decode_bits()
# 503
bits_503 = decoder.decode_bits()
bits_503 += decoder.decode_bits()
# 504
bits_504 = decoder.decode_bits()
bits_504 += decoder.decode_bits()
# 505
bits_505 = decoder.decode_bits()
bits_505 += decoder.decode_bits()
# 506
bits_506 = decoder.decode_bits()
bits_506 += decoder.decode_bits()
bSendCommand = False
if switch.get_active():
# %MW552:X2 START INIET. DA REMOTO
bSendCommand = not bits_502[7]
bits_552[2] = True
bits_552[3] = False
bits_552[14] = True
else:
# %MW552:X2 STOP INIET. DA REMOTO
bSendCommand = bits_502[7]
bits_552[2] = False
bits_552[3] = True
bits_552[14] = False
builder = BinaryPayloadBuilder(endian=Endian.Little)
# builder.add_bits(bits_502)
builder.add_bits(bits_552)
reg_552 = builder.to_registers()
rr.registers[52:53] = reg_552
self.p_count += 1
rr.registers[50] = self.p_count
if bSendCommand:
self.client_p.write_registers(500, rr.registers,unit=1)
if bits_552[2]:
bits_552[2] = False
builder = BinaryPayloadBuilder(endian=Endian.Little)
# builder.add_bits(bits_502)
builder.add_bits(bits_552)
reg_552 = builder.to_registers()
self.client_p.write_register(552, reg_552[0])
print "pulsante rilasciato"
self.client_p.close()
示例6: testPayloadDecoderCoilFactory
def testPayloadDecoderCoilFactory(self):
""" Test the payload decoder reset functionality """
payload = [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]
decoder = BinaryPayloadDecoder.fromCoils(payload, endian=Endian.Little)
encoded = "\x11\x88"
self.assertEqual(encoded, decoder.decode_string(2))
decoder = BinaryPayloadDecoder.fromCoils(payload, endian=Endian.Big)
encoded = "\x11\x88"
self.assertEqual(encoded, decoder.decode_string(2))
self.assertRaises(ParameterException, lambda: BinaryPayloadDecoder.fromCoils("abcd"))
示例7: testPayloadDecoderRegisterFactory
def testPayloadDecoderRegisterFactory(self):
""" Test the payload decoder reset functionality """
payload = [1, 2, 3, 4]
decoder = BinaryPayloadDecoder.fromRegisters(payload, endian=Endian.Little)
encoded = "\x00\x01\x00\x02\x00\x03\x00\x04"
self.assertEqual(encoded, decoder.decode_string(8))
decoder = BinaryPayloadDecoder.fromRegisters(payload, endian=Endian.Big)
encoded = "\x00\x01\x00\x02\x00\x03\x00\x04"
self.assertEqual(encoded, decoder.decode_string(8))
self.assertRaises(ParameterException, lambda: BinaryPayloadDecoder.fromRegisters("abcd"))
示例8: on_btnSetPump_clicked
def on_btnSetPump_clicked(self,button):
rr_p = self.client_p.read_holding_registers(500,100,unit=1)
decoder = BinaryPayloadDecoder.fromRegisters(rr_p.registers[52:53],endian=Endian.Little)
bits_552 = decoder.decode_bits()
bits_552 += decoder.decode_bits()
self.pmax = self.adjustPMax.get_value()
_qmax = self.adjustQMax.get_value()
self.p_count += 1
rr_p.registers[50] = self.p_count
rr_p.registers[60] = int(self.pmax)
if self.chkPAna.get_active():
self.qmax = getFlowRateAsVolts(_qmax)
v = getVoltsFromFlowRate(self.qmax)
print "_qmax => {0} self.qmax => {1} c => {2}".format(_qmax, self.qmax, v)
rr_p.registers[64] = self.qmax
rr_p.registers[62] = int(_qmax/litCiclo)
bits_552[12] = True
else:
self.qmax = _qmax
rr_p.registers[62] = int(self.qmax)
rr_p.registers[64] = cicli_volt[int(self.qmax)]
bits_552[12] = False
b_builder = BinaryPayloadBuilder(endian=Endian.Little)
# builder.add_bits(bits_502)
b_builder.add_bits(bits_552)
reg_552 = b_builder.to_registers()
rr_p.registers[52:53] = reg_552
rr_p = self.client_p.write_registers(500,rr_p.registers,unit=1)
示例9: read
def read(self):
count = COUNTS.get(self.data_type)
if not count:
raise ValueError('Unsupported data type {}'.format(self.data_type))
_logger.debug('read register: {}, count: {}, slave: {}, function: {}'.format(self.register_addr, count, self.slave_id, self.function_code))
if self.function_code == 3:
result = self.client.read_holding_registers(self.register_addr, count, unit=self.slave_id)
elif self.function_code == 4:
result = self.client.read_input_registers(self.register_addr, count, unit=self.slave_id)
else:
raise ValueError('Unsupported function code {}'.format(self.function_code))
if result is None:
raise IOError('No modbus reponse')
if isinstance(result, ExceptionResponse):
raise IOError(str(result))
d = BinaryPayloadDecoder.fromRegisters(result.registers, endian=self.endian)
if self.data_type == '16bit_int':
value = d.decode_16bit_int()
elif self.data_type == '16bit_uint':
value = d.decode_16bit_uint()
elif self.data_type == '32bit_int':
value = d.decode_32bit_int()
elif self.data_type == '32bit_uint':
value = d.decode_32bit_uint()
elif self.data_type == '32bit_float':
value = d.decode_32bit_float()
elif self.data_type == '64bit_float':
value = d.decode_64bit_float()
else:
raise ValueError('Unsupported data type {}'.format(self.data_type))
return value
示例10: decode
def decode(self, formatters, byte_order='big', word_order='big'):
"""
Decode the register response to known formatters.
:param formatters: int8/16/32/64, uint8/16/32/64, float32/64
:param byte_order: little/big
:param word_order: little/big
:return: Decoded Value
"""
# Read Holding Registers (3)
# Read Input Registers (4)
# Read Write Registers (23)
if not isinstance(formatters, (list, tuple)):
formatters = [formatters]
if self.function_code not in [3, 4, 23]:
print_formatted_text(
HTML("<red>Decoder works only for registers!!</red>"))
return
byte_order = (Endian.Little if byte_order.strip().lower() == "little"
else Endian.Big)
word_order = (Endian.Little if word_order.strip().lower() == "little"
else Endian.Big)
decoder = BinaryPayloadDecoder.fromRegisters(self.data.get('registers'),
byteorder=byte_order,
wordorder=word_order)
for formatter in formatters:
formatter = FORMATTERS.get(formatter)
if not formatter:
print_formatted_text(
HTML("<red>Invalid Formatter - {}"
"!!</red>".format(formatter)))
return
decoded = getattr(decoder, formatter)()
self.print_result(decoded)
示例11: checkPump
def checkPump(self,client_p):
self.p_count += 1
rq = client_p.write_register(550,self.p_count,unit=1)
if rq.function_code < 0x80:
rr_p = client_p.read_holding_registers(500,100,unit=1)
if len(rr_p.registers)==100 and rr_p.registers[0]==self.p_count:
decoder = BinaryPayloadDecoder.fromRegisters(rr_p.registers[2:7],endian=Endian.Little)
# 502
bits_502 = decoder.decode_bits()
bits_502 += decoder.decode_bits()
# 503
bits_503 = decoder.decode_bits()
bits_503 += decoder.decode_bits()
# 504
bits_504 = decoder.decode_bits()
bits_504 += decoder.decode_bits()
# 505
bits_505 = decoder.decode_bits()
bits_505 += decoder.decode_bits()
# 506
bits_506 = decoder.decode_bits()
bits_506 += decoder.decode_bits()
if bits_502[7]:
builder.get_object("switchPumpStatus").set_active(True)
else:
builder.get_object("switchPumpStatus").set_active(False)
if bits_502[4] == False and bits_502[10] == True:
builder.get_object("switchPumpStatus").set_sensitive(True)
else:
builder.get_object("switchPumpStatus").set_sensitive(False)
self.setPumpFlowAndPressure()
示例12: requestLoop
def requestLoop(self):
meterreadings = {}
try:
if (self.client.connect() is False):
print('not connected')
self.client = self.client.connect()
print('trying to connecto to ' + str(self.pfcIp))
#==============================================================================
# Read current timestamp from PFC
#==============================================================================
timestampSys = round(time.time() * 1000)
result2 = self.client.read_holding_registers(4, 4)
decoder = BinaryPayloadDecoder.fromRegisters(result2.registers, endian=Endian.Little)
timestampPFC = decoder.decode_64bit_int()
#==============================================================================
# Reads the values from modbus registers clamp by clamp
# and buffers the results in meterreadings{}
# It is not possible to read all registers in one request because of the limitation of the Modbus-Message size to 255kb
# When the results of all clamps are buffered, they are published
#==============================================================================
result = self.client.read_coils(16, 4)
meterreadings = {'shStarr': result.bits[0],
'sh4QS': result.bits[1],
'speicherSh': result.bits[2],
'speicher4QS': result.bits[3]}
#==============================================================================
# standardize both TimestampPFC and TimestampSYS precision to be millisecond
#==============================================================================
meterreadingsToCompare = {}
meterreadingsToCompare = meterreadings
self.oldState.pop('TimestampPFC', None)
self.oldState.pop('TimestampSYS', None)
self.elapsedTime = self.elapsedTime + 1
if (self.oldState != meterreadingsToCompare) or (self.elapsedTime >= 60):
self.elapsedTime = 0
self.oldState = meterreadingsToCompare
meterreadings['TimestampPFC'] = str(timestampPFC)[0:13]
meterreadings['TimestampSYS'] = round(time.time() * 1000)
self.publish(u'eshl.wago.v1.readout.misc.4qs', json.dumps(meterreadings, sort_keys=True))
self.publish(u'eshl.wago.v2.readout.misc.4qs', meterreadings)
#==============================================================================
# If there is no connection to the pfc-modbus slave or no connection to the pfc at all
# the blankDataSet is published
#==============================================================================
#==============================================================================
# except ConnectionException as connErr:
# for x in range(0, len(self.clamps)):
# meterreadings[self.clamps[x]] = json.dumps(self.blankDataSetGen(), sort_keys=True)
# self.publish(u'org.eshl.wago.readout.meter.494', json.dumps(meterreadings,sort_keys=True))
# print(str(connErr))
#==============================================================================
except Exception as err:
print("error: {}".format(err), file=sys.stdout)
traceback.print_exc(file=sys.stdout)
示例13: start_iniettore
def start_iniettore(p_client):
b_ok = False
n_numReg = 5
# leggo 502 a 506 per verificare bit di controllo
p_rr = p_client.read_holding_registers(502,n_numReg,unit=1)
decoder = BinaryPayloadDecoder.fromRegisters(p_rr.registers,endian=Endian.Little)
reg={}
regnum = 502
for i in range(n_numReg):
bits_50x = decoder.decode_bits()
bits_50x += decoder.decode_bits()
reg[regnum+i] = bits_50x
if reg[502][4]:
log.error("Pompa in allarme")
else:
if reg[502][6]:
log.debug("Pompa olio on")
if reg[502][7]:
log.error("Ciclo Iniettore ON")
else:
log.debug("Ciclo Iniettore OFF")
# %MW502:X10 Macchina pronta per comando remoto
b_ok = reg[502][10]
if b_ok:
log.debug("Macchina pronta per comando remoto")
else:
log.error(u"Macchina non è pronta per comando remoto")
b_ok &= check_alarms(reg[504])
if b_ok:
log.debug("...nessun allarme rilevato")
p_comandi_remoto = p_client.read_holding_registers(560,3,unit=1)
remote_reg = [0]*3
remote_reg = p_comandi_remoto.registers
log.debug("COMANDO BAR DA REMOTO IMPOSTATO a %d" % remote_reg[0]) # %MW560 16 bit 0-100 bar COMANDO BAR DA REMOTO
log.debug("COMANDO NUMERO CICLI MINUTO DA REMOTO a %d" % remote_reg[2]) # %MW562 16 bit < 40 COMANDO NUMERO CICLI MINUTO DA REMOTO
remote_reg[0] = DEFAULT_BAR
remote_reg[2] = DEFAULT_CICLI
rq = p_client.write_registers(560, remote_reg,unit=1)
b_ok = rq.function_code < 0x80 # test that we are not an error
if b_ok:
bits_552 = [False]*16
bits_552[2] = True # %MW552:X2 START INIET. DA REMOTO
builder = BinaryPayloadBuilder(endian=Endian.Little)
builder.add_bits(bits_552)
reg_552 = builder.to_registers()
rq = p_client.write_register(552, reg_552[0],unit=1)
b_ok = rq.function_code < 0x80 # test that we are not an error
else:
log.error("start_iniettore SET Comandi BAR e CICLI REMOTO fallito!")
else:
log.debug("...verificare allarmi rilevati")
else:
log.error("Pompa olio OFF")
return b_ok
示例14: __decodeData
def __decodeData(self, data):
"""Decode MODBUS data to float
Function decodes a list of MODBUS 32bit float data passed to it
into its respective list of floats.
Arguments:
:param data: Data to be decoded
:type data: list
"""
returnData = [0]*(len(data)/2)
decoder = BinaryPayloadDecoder.fromRegisters(data, endian=Endian.Little)
for i in range(0,len(data)/2):
returnData[i] = round(decoder.decode_32bit_float(),2)
return returnData
示例15: readChannels
def readChannels():
# voltage phase 1 to neutral
print "New measurement readings: ", int(time.time())
listValues = list()
for c in listChannels:
handle = client.read_holding_registers(c['register'],c['words'],unit=c['unit'])
# print c['description'], ":"
if c['words'] > 1:
decoder = BinaryPayloadDecoder.fromRegisters(handle.registers, endian=Endian.Big)
value = decoder.decode_32bit_int()/float(c['factor'])
else:
value = handle.registers[0]/float(c['factor'])
#print c['description'], ":", str(value)
listValues.append(value)
for i, channel in enumerate(listChannels):
# print channel['description'],":", channel['uuid'], int(time.time()*1000), listValues[i]
# Here fire values into VZ middleware
addValue(channel['uuid'], int(time.time()*1000), listValues[i])