本文整理汇总了Python中pymodbus.compat.byte2int函数的典型用法代码示例。如果您正苦于以下问题:Python byte2int函数的具体用法?Python byte2int怎么用?Python byte2int使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了byte2int函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: calculateRtuFrameSize
def calculateRtuFrameSize(cls, buffer):
''' Calculates the size of the message
:param buffer: A buffer containing the data that have been received.
:returns: The number of bytes in the response.
'''
hi_byte = byte2int(buffer[2])
lo_byte = byte2int(buffer[3])
return (hi_byte << 16) + lo_byte + 6
示例2: dataReceived
def dataReceived(self, data):
''' Callback when we receive any data
:param data: The data sent by the client
'''
if _logger.isEnabledFor(logging.DEBUG):
_logger.debug(' '.join([hex(byte2int(x)) for x in data]))
if not self.factory.control.ListenOnly:
unit_address = byte2int(data[0])
if unit_address in self.factory.store:
self.framer.processIncomingPacket(data, self._execute)
示例3: decode
def decode(self, data):
''' Decodes a the response
Since the identifier is device dependent, we just return the
raw value that a user can decode to whatever it should be.
:param data: The packet data to decode
'''
self.byte_count = byte2int(data[0])
self.identifier = data[1:self.byte_count + 1]
status = byte2int(data[-1])
self.status = status == ModbusStatus.SlaveOn
示例4: execute
def execute(self, request):
''' Starts the producer to send the next request to
consumer.write(Frame(request))
'''
retries = self.retries
request.transaction_id = self.getNextTID()
_logger.debug("Running transaction %d" % request.transaction_id)
self.client.framer.resetFrame()
expected_response_length = None
if hasattr(request, "get_response_pdu_size"):
response_pdu_size = request.get_response_pdu_size()
if isinstance(self.client.framer, ModbusAsciiFramer):
response_pdu_size = response_pdu_size * 2
if response_pdu_size:
expected_response_length = self._calculate_response_length(response_pdu_size)
while retries > 0:
try:
last_exception = None
self.client.connect()
packet = self.client.framer.buildPacket(request)
if _logger.isEnabledFor(logging.DEBUG):
_logger.debug("send: " + " ".join([hex(byte2int(x)) for x in packet]))
self._send(packet)
# exception = False
result = self._recv(expected_response_length or 1024)
if not result and self.retry_on_empty:
retries -= 1
continue
if _logger.isEnabledFor(logging.DEBUG):
_logger.debug("recv: " + " ".join([hex(byte2int(x)) for x in result]))
self.client.framer.processIncomingPacket(result, self.addTransaction)
break
except (socket.error, ModbusIOException, InvalidMessageRecievedException) as msg:
self.client.close()
_logger.debug("Transaction failed. (%s) " % msg)
retries -= 1
last_exception = msg
response = self.getTransaction(request.transaction_id)
if not response:
if len(self.transactions):
response = self.getTransaction(tid=0)
else:
last_exception = last_exception or ("No Response "
"received from the remote unit")
response = ModbusIOException(last_exception)
return response
示例5: checkFrame
def checkFrame(self):
'''
Check if the next frame is available. Return True if we were
successful.
'''
try:
self.populateHeader()
frame_size = self.__header['len']
data = self.__buffer[:frame_size - 2]
crc = self.__buffer[frame_size - 2:frame_size]
crc_val = (byte2int(crc[0]) << 8) + byte2int(crc[1])
return checkCRC(data, crc_val)
except (IndexError, KeyError):
return False
示例6: _check_response
def _check_response(self, response):
''' Checks if the response is a Modbus Exception.
'''
if isinstance(self.client.framer, ModbusSocketFramer):
if len(response) >= 8 and byte2int(response[7]) > 128:
return False
elif isinstance(self.client.framer, ModbusAsciiFramer):
if len(response) >= 5 and int(response[3:5], 16) > 128:
return False
elif isinstance(self.client.framer, (ModbusRtuFramer, ModbusBinaryFramer)):
if len(response) >= 2 and byte2int(response[1]) > 128:
return False
return True
示例7: processIncomingPacket
def processIncomingPacket(self, data, callback):
''' The new packet processing pattern
This takes in a new request packet, adds it to the current
packet stream, and performs framing on it. That is, checks
for complete messages, and once found, will process all that
exist. This handles the case when we read N + 1 or 1 / N
messages at a time instead of 1.
The processed and decoded messages are pushed to the callback
function to process and send.
:param data: The new packet data
:param callback: The function to send results to
'''
_logger.debug(' '.join([hex(byte2int(x)) for x in data]))
self.addToFrame(data)
while True:
if self.isFrameReady():
if self.checkFrame():
self._process(callback)
else: self.resetFrame()
else:
if len(self.__buffer):
# Possible error ???
if self.__header['len'] < 2:
self._process(callback, error=True)
break
示例8: execute
def execute(self, request=None):
"""
Executes a transaction
:param request: Request to be written on to the bus
:return:
"""
request.transaction_id = self.transaction.getNextTID()
def callback(*args):
LOGGER.debug("in callback - {}".format(request.transaction_id))
while True:
waiting = self.stream.connection.in_waiting
if waiting:
data = self.stream.connection.read(waiting)
LOGGER.debug(
"recv: " + " ".join([hex(byte2int(x)) for x in data]))
unit = self.framer.decode_data(data).get("uid", 0)
self.framer.processIncomingPacket(
data,
self._handle_response,
unit,
tid=request.transaction_id
)
break
packet = self.framer.buildPacket(request)
LOGGER.debug("send: " + " ".join([hex(byte2int(x)) for x in packet]))
self.stream.write(packet, callback=callback)
f = self._build_response(request.transaction_id)
return f
示例9: _helper
def _helper(self, data):
'''
This factory is used to generate the correct response object
from a valid response packet. This decodes from a list of the
currently implemented request types.
:param data: The response packet to decode
:returns: The decoded request or an exception response object
'''
fc_string = function_code = byte2int(data[0])
if function_code in self.__lookup:
fc_string = "%s: %s" % (
str(self.__lookup[function_code]).split('.')[-1].rstrip("'>"),
function_code
)
_logger.debug("Factory Response[%s]" % fc_string)
response = self.__lookup.get(function_code, lambda: None)()
if function_code > 0x80:
code = function_code & 0x7f # strip error portion
response = ExceptionResponse(code, ecode.IllegalFunction)
if not response:
raise ModbusException("Unknown response %d" % function_code)
response.decode(data[1:])
if hasattr(response, 'sub_function_code'):
lookup = self.__sub_lookup.get(response.function_code, {})
subtype = lookup.get(response.sub_function_code, None)
if subtype: response.__class__ = subtype
return response
示例10: _helper
def _helper(self, data):
"""
This factory is used to generate the correct request object
from a valid request packet. This decodes from a list of the
currently implemented request types.
:param data: The request packet to decode
:returns: The decoded request or illegal function request object
"""
function_code = byte2int(data[0])
request = self.__lookup.get(function_code, lambda: None)()
if not request:
_logger.debug("Factory Request[%d]" % function_code)
request = IllegalFunctionRequest(function_code)
else:
fc_string = "%s: %s" % (
str(self.__lookup[function_code]).split('.')[-1].rstrip(
"'>"),
function_code
)
_logger.debug("Factory Request[%s]" % fc_string)
request.decode(data[1:])
if hasattr(request, 'sub_function_code'):
lookup = self.__sub_lookup.get(request.function_code, {})
subtype = lookup.get(request.sub_function_code, None)
if subtype: request.__class__ = subtype
return request
示例11: decode
def decode(self, data):
''' Decodes response pdu
:param data: The packet data to decode
'''
self.byte_count = byte2int(data[0])
self.bits = unpack_bitstring(data[1:])
示例12: handle
def handle(self):
''' Callback when we receive any data
'''
reset_frame = False
while self.running:
try:
data, self.request = self.request
if not data:
self.running = False
if _logger.isEnabledFor(logging.DEBUG):
_logger.debug(' '.join([hex(byte2int(x)) for x in data]))
# if not self.server.control.ListenOnly:
self.framer.processIncomingPacket(data, self.execute)
except socket.timeout: pass
except socket.error as msg:
_logger.error("Socket error occurred %s" % msg)
self.running = False
reset_frame = True
except Exception as msg:
_logger.error(msg)
self.running = False
reset_frame = True
finally:
if reset_frame:
self.framer.resetFrame()
reset_frame = False
示例13: handle
def handle(self):
'''Callback when we receive any data, until self.running becomes not True. Blocks indefinitely
awaiting data. If shutdown is required, then the global socket.settimeout(<seconds>) may be
used, to allow timely checking of self.running. However, since this also affects socket
connects, if there are outgoing socket connections used in the same program, then these will
be prevented, if the specfied timeout is too short. Hence, this is unreliable.
To respond to Modbus...Server.server_close() (which clears each handler's self.running),
derive from this class to provide an alternative handler that awakens from time to time when
no input is available and checks self.running. Use Modbus...Server( handler=... ) keyword
to supply the alternative request handler class.
'''
while self.running:
try:
data = self.request.recv(1024)
if not data: self.running = False
if _logger.isEnabledFor(logging.DEBUG):
_logger.debug(' '.join([hex(byte2int(x)) for x in data]))
# if not self.server.control.ListenOnly:
self.framer.processIncomingPacket(data, self.execute)
except socket.timeout as msg:
if _logger.isEnabledFor(logging.DEBUG):
_logger.debug("Socket timeout occurred %s", msg)
pass
except socket.error as msg:
_logger.error("Socket error occurred %s" % msg)
self.running = False
except:
_logger.error("Socket exception occurred %s" % traceback.format_exc() )
self.running = False
示例14: populateHeader
def populateHeader(self):
''' Try to set the headers `uid`, `len` and `crc`.
This method examines `self.__buffer` and writes meta
information into `self.__header`. It calculates only the
values for headers that are not already in the dictionary.
Beware that this method will raise an IndexError if
`self.__buffer` is not yet long enough.
'''
self.__header['uid'] = byte2int(self.__buffer[0])
func_code = byte2int(self.__buffer[1])
pdu_class = self.decoder.lookupPduClass(func_code)
size = pdu_class.calculateRtuFrameSize(self.__buffer)
self.__header['len'] = size
self.__header['crc'] = self.__buffer[size - 2:size]
示例15: checkFrame
def checkFrame(self):
"""
Check if the next frame is available.
Return True if we were successful.
1. Populate header
2. Discard frame if UID does not match
"""
try:
self.populateHeader()
frame_size = self._header['len']
data = self._buffer[:frame_size - 2]
crc = self._buffer[frame_size - 2:frame_size]
crc_val = (byte2int(crc[0]) << 8) + byte2int(crc[1])
return checkCRC(data, crc_val)
except (IndexError, KeyError):
return False