def SBusClientFieldResponse(cmdcode, telegramattr, msgsequence, msgdata):
	"""Construct the report for a SBus field message response.
	cmdcode (integer) = Command code.
	telegramattr (integer) = Telegram attribute.
	msgsequence (integer) = Message sequence.
	msgdata (string) = The response data as a binary string.
	"""

	try:
		if cmdcode in [2, 3, 5, 11, 13]:
			reportreqdata = _BoolList2Str(ModbusDataLib.bin2boollist(msgdata))
		elif cmdcode in [6, 14]:
			reportreqdata = binascii.hexlify(msgdata)
		else:
			reportreqdata = 'No data.'

		# This splits the string up into groups separated by 
		# spaces to allow line breaks on the report web page.
		reportstr = BreakString(reportreqdata)

		return _sbsclientrespreportstr % (telegramattr, msgsequence, reportstr)


	# If there was an error, we just ignore it and log some default data.
	except:
		return _sbsclientrespreportstr % (0, 0, 0, 'Response data error.')
def SBusClientFieldRequest(msgsequence, stnaddr, cmdcode, dataaddr, datacount,
                           msgdata):
    """Construct the report for a SBus field message request.
	msgsequence (integer) = Message sequence.
	stnaddr (integer) = Station address.
	cmdcode (integer) = Command code.
	dataaddr (integer) = Starting data table address.
	datacount (integer) = Number of data elements.
	msgdata (string) = The raw binary string containing the message data.
	"""

    try:
        if cmdcode in [2, 3, 5, 6]:
            reportreqdata = ''
        elif cmdcode in [11, 13]:
            reportreqdata = _BoolList2Str(ModbusDataLib.bin2boollist(msgdata))
        elif cmdcode == 14:
            reportreqdata = binascii.hexlify(msgdata)
        else:
            reportreqdata = 'No data.'

        # This splits the string up into groups separated by
        # spaces to allow line breaks on the report web page.
        reportstr = BreakString(reportreqdata)

        return _sbsclientreqreportstr % (msgsequence, stnaddr, cmdcode,
                                         dataaddr, datacount, reportstr)

    # If there was an error, we just ignore it and log some default data.
    except:
        return _sbsclientreqreportstr % (0, 0, 0, 0, 0, 'Request data error.')
def SBusClientFieldResponse(cmdcode, telegramattr, msgsequence, msgdata):
    """Construct the report for a SBus field message response.
	cmdcode (integer) = Command code.
	telegramattr (integer) = Telegram attribute.
	msgsequence (integer) = Message sequence.
	msgdata (string) = The response data as a binary string.
	"""

    try:
        if cmdcode in [2, 3, 5, 11, 13]:
            reportreqdata = _BoolList2Str(ModbusDataLib.bin2boollist(msgdata))
        elif cmdcode in [6, 14]:
            reportreqdata = binascii.hexlify(msgdata)
        else:
            reportreqdata = 'No data.'

        # This splits the string up into groups separated by
        # spaces to allow line breaks on the report web page.
        reportstr = BreakString(reportreqdata)

        return _sbsclientrespreportstr % (telegramattr, msgsequence, reportstr)

    # If there was an error, we just ignore it and log some default data.
    except:
        return _sbsclientrespreportstr % (0, 0, 0, 'Response data error.')
def SBusClientFieldRequest(msgsequence, stnaddr, cmdcode, dataaddr, datacount, msgdata):
	"""Construct the report for a SBus field message request.
	msgsequence (integer) = Message sequence.
	stnaddr (integer) = Station address.
	cmdcode (integer) = Command code.
	dataaddr (integer) = Starting data table address.
	datacount (integer) = Number of data elements.
	msgdata (string) = The raw binary string containing the message data.
	"""

	try:
		if cmdcode in [2, 3, 5, 6]:
			reportreqdata = ''
		elif cmdcode in [11, 13]:	
			reportreqdata = _BoolList2Str(ModbusDataLib.bin2boollist(msgdata))
		elif cmdcode == 14:
			reportreqdata = binascii.hexlify(msgdata)
		else:
			reportreqdata = 'No data.'

		# This splits the string up into groups separated by 
		# spaces to allow line breaks on the report web page.
		reportstr = BreakString(reportreqdata)

		return _sbsclientreqreportstr % (msgsequence, stnaddr, cmdcode, dataaddr, datacount, reportstr)

	# If there was an error, we just ignore it and log some default data.
	except:
		return _sbsclientreqreportstr % (0, 0, 0, 0, 0, 'Request data error.')
def ModbusClientFieldRequest(transid, uid, functioncode, start, qty, msgdata):
	"""Construct the report for a Modbus/TCP field message request.
	transid (integer) = The transaction id. 
	uid (integer) = The unit id. 
	functioncode (integer) = The function code.
	start (integer) = The starting data table address.
	qty (integer) = The number of items requested.
	msgdata (string) = The raw binary string containing the message data.
	"""
	try:
		if functioncode in [1, 2, 3, 4]:
			reportreqdata = ''
		elif functioncode in [5, 6, 16]:
			reportreqdata = binascii.hexlify(msgdata)
		elif (functioncode == 15):
			reportreqdata = _BoolList2Str(ModbusDataLib.bin2boollist(msgdata))
		else:
			reportreqdata = 'No data.'

		# This splits the string up into groups separated by 
		# spaces to allow line breaks on the report web page.
		reportstr = BreakString(reportreqdata)

		return _reqreportstr % (transid, uid, functioncode, start, qty, reportstr)

	# If there was an error, we just ignore it and log some default data.
	except:
		return _reqreportstr % (0, 0, 0, 0, 0, 'Request data error.')
def ModbusClientFieldResponse(transid, functioncode, msgdata):
	"""Construct the report for a Modbus/TCP field message request.
	transid (integer) = The transaction id. 
	functioncode (integer) = The function code.
	msgdata (string) = The response data as a binary string.
	"""

	try:
		if functioncode in [1, 2]:
			reportrespdata = _BoolList2Str(ModbusDataLib.bin2boollist(msgdata))
		elif functioncode in [3, 4, 5, 6, 15, 16]:
			reportrespdata = binascii.hexlify(msgdata)
		elif functioncode > 127:
			reportrespdata = binascii.hexlify(msgdata)
		else:
			reportrespdata = 'No data.'

		# This splits the string up into groups separated by 
		# spaces to allow line breaks on the report web page.
		reportstr = BreakString(reportrespdata)

		return _respreportstr % (transid, functioncode, reportstr)

	# If there was an error, we just ignore it and log some default data.
	except:
		return _respreportstr % (0, 0, 'Response data error.')
Ejemplo n.º 7
0
def ModbusClientFieldResponse(transid, functioncode, msgdata):
    """Construct the report for a Modbus/TCP field message request.
	transid (integer) = The transaction id. 
	functioncode (integer) = The function code.
	msgdata (string) = The response data as a binary string.
	"""

    try:
        if functioncode in [1, 2]:
            reportrespdata = _BoolList2Str(ModbusDataLib.bin2boollist(msgdata))
        elif functioncode in [3, 4, 5, 6, 15, 16]:
            reportrespdata = binascii.hexlify(msgdata)
        elif functioncode > 127:
            reportrespdata = binascii.hexlify(msgdata)
        else:
            reportrespdata = 'No data.'

        # This splits the string up into groups separated by
        # spaces to allow line breaks on the report web page.
        reportstr = BreakString(reportrespdata)

        return _respreportstr % (transid, functioncode, reportstr)

    # If there was an error, we just ignore it and log some default data.
    except:
        return _respreportstr % (0, 0, 'Response data error.')
Ejemplo n.º 8
0
def ModbusClientFieldRequest(transid, uid, functioncode, start, qty, msgdata):
    """Construct the report for a Modbus/TCP field message request.
	transid (integer) = The transaction id. 
	uid (integer) = The unit id. 
	functioncode (integer) = The function code.
	start (integer) = The starting data table address.
	qty (integer) = The number of items requested.
	msgdata (string) = The raw binary string containing the message data.
	"""
    try:
        if functioncode in [1, 2, 3, 4]:
            reportreqdata = ''
        elif functioncode in [5, 6, 16]:
            reportreqdata = binascii.hexlify(msgdata)
        elif (functioncode == 15):
            reportreqdata = _BoolList2Str(ModbusDataLib.bin2boollist(msgdata))
        else:
            reportreqdata = 'No data.'

        # This splits the string up into groups separated by
        # spaces to allow line breaks on the report web page.
        reportstr = BreakString(reportreqdata)

        return _reqreportstr % (transid, uid, functioncode, start, qty,
                                reportstr)

    # If there was an error, we just ignore it and log some default data.
    except:
        return _reqreportstr % (0, 0, 0, 0, 0, 'Request data error.')
Ejemplo n.º 9
0
def GetServerData(cmd, adr, qty):
	MsgSeqCounter.incseq()
	# Send the request.
	client.SendRequest(MsgSeqCounter.getseq(), 1, cmd, qty, adr)
	# Get the reply.
	TeleAttr, MsgSeq, MsgData = client.ReceiveResponse()
	# Decode the data.
	if (cmd in (2, 3, 5)):
		try:
			values = ModbusDataLib.bin2boollist(MsgData)
		except:
			return []
	elif (cmd == 6):
		try:
			values = SBusMsg.signedbin2int32list(MsgData)
		except:
			return []
	else:
		print('Bad command code %s when reading data.' % cmd)
		return []
	return values
Ejemplo n.º 10
0
def GetServerData(func, adr, qty):
	try:
		# Send the request.
		client.SendRequest(1, 1, func, adr, qty)
		# Get the reply.
		TransID, rfunct, Address, Qty, MsgData, Excode = client.ReceiveResponse()
	except:
		print('Demosim - lost contact with server - exiting')
		sys.exit()

	# Decode the data.
	if (rfunct in [1, 2]):
		values = ModbusDataLib.bin2boollist(MsgData)
	elif (rfunct in [3, 4]):
		values = ModbusDataLib.signedbin2intlist(MsgData)
	else:
		print('Demosim - Bad function code %s when reading data.' % rfunct)
		# Provide a default based on the sending function.
		if (func in [1, 2]):
			values = [False] * 8
		elif (funct in [3, 4]):
			values = [0] * 8
	return values
Ejemplo n.º 11
0
	def GetCoilsBool(self, addr):
		"""Read coils from the host (function 1).
		addr (integer) = Modbus coil address.
		"""
		return ModbusDataLib.bin2boollist(self._ModbusRequest(1, addr, 1, None))[0]
Ejemplo n.º 12
0
	def GetDiscreteInputsBool(self, addr):
		"""Read discrete inputs from the host (function 2).
		addr (integer) = Modbus discrete inputs address.
		"""
		return ModbusDataLib.bin2boollist(self._ModbusRequest(2, addr, 1, None))[0]
Ejemplo n.º 13
0
	def GetFlagsBool(self, addr):
		"""Read flags from the host (command 2).
		addr (integer) = SBus flags address.
		"""
		return ModbusDataLib.bin2boollist(self._SBusRequest(2, addr, 1, None))[0]
Ejemplo n.º 14
0
	def GetOutputsBool(self, addr):
		"""Read outputs from the host (command 5).
		addr (integer) = SBus outputs address.
		"""
		return ModbusDataLib.bin2boollist(self._SBusRequest(5, addr, 1, None))[0]
Ejemplo n.º 15
0
	def NextCommand(self, readtable, servercmd):
		"""This should execute the next command, whatever it is. This
		is called regularly by GenClient.
		Parameters: readtable (dict) = A dictionary containing a mirror of the
			requested portion of the server data table. E.g.
			{'coil' : [True, False, True, True], 'inp' : [True, False, True, True],
			'inpreg' : [], 'holdingreg' : [1234, 5678]}

			servercmd (string) = A command from the server. This will 
				consist of one of the following:
				'run' = Run normally.
				'pause' = Pause operation.
				'restart' = A restart is requested. The restart 
					request will remain in effect until new
					parameters are loaded.

		Returns: dict, float = 
			- A dictionary in the same format as the "readtable" input parameter. This 
				will contain the data to be written to the server.
			- The time in seconds to wait before running this function again.

			Data table items in excess of those configured for transfer will be ignored.
		"""
		# First check if we've got a good parameter set.
		if not self._ConfigOK:
			# Set the connection status.
			self._ConnectStatus = 'stopped'
			nextpoll = 1.0

			return self._WriteTable, nextpoll


		# Get the next command.
		try:
			cmdname, cmdvalue = self._CommandIter.next()
			nextpoll = self._CommandTime
		except StopIteration:
			self._CommandIter = iter(self._CommandList)
			cmdname, cmdvalue = self._CommandIter.next()
			nextpoll = self._RepeatTime


		# See what the command says we should do. A typical command looks like this:
		# [('action', 'poll'), ('stn', 1), ('cmd', 3), ('remoteaddr', 0), 
		# 		('qty', 10), ('datatype', 'coil'), ('dataoffset', 0)]		
		cmdexp = dict(cmdvalue)
		cmd = cmdexp['cmd']
		datatype = cmdexp['datatype']
		dataoffset = cmdexp['dataoffset']
		qty = cmdexp['qty']

		# This is a write command, so we need data.
		# Write flags or outputs.
		if cmd in (11, 13):
			msgdata = ModbusDataLib.boollist2bin(readtable[datatype][dataoffset:dataoffset + qty])
		# Write registers. SBus registers are 32 bit, so we need 2 Modbus 
		# registers for each SBus register.
		elif cmd == 14:
			msgdata = ModbusDataLib.signedintlist2bin(readtable[datatype][dataoffset:dataoffset + (qty * 2)])
		else:
			msgdata = ''

		# #####################################
		# If we have an error, then bail out, close the socket and set an error
		# code. Set the client to None so we will re-initialise on the next round. 

		# Create the client if necessary.
		if self._SBusClient == None:
			self._SBusClient = SBusSimpleClient.SBusSimpleClient(self._Host, self._Port, self._TimeOut)

		self._MsgSeq += 1

		try:
			# Send the request.
			self._SBusClient.SendRequest(self._MsgSeq, cmdexp['stn'], cmd, qty, cmdexp['remoteaddr'], msgdata)
			# Get the response.
			telegramattr, recvmsgseq, recvdata = self._SBusClient.ReceiveResponse()
		# If we have an error, bail out here.
		except:
			self._SBusClient = None
			self._ConnectStatus = 'faulted'
			self._AddCmdStatus(cmdname, 'connection')
			# Exit here if error.
			return {}, 0.5

		# #####################################


		# This is a read command, so we need to save the data.
		# Read flags, inputs, or outputs.
		if (cmd in (2, 3, 5)) and (telegramattr == 1):
			booldata = ModbusDataLib.bin2boollist(recvdata)
			self._WriteTable[datatype][dataoffset:dataoffset + qty] = booldata[:qty]
			# Set the connection status.
			self._ConnectStatus = 'running'
			self._AddCmdStatus(cmdname, 'ok')
		# Read registers.
		elif (cmd == 6) and (telegramattr == 1):
			regdata = ModbusDataLib.signedbin2intlist(recvdata)
			# SBus registers are twice the size of Modbus registers.
			self._WriteTable[datatype][dataoffset:dataoffset + (qty * 2)] = regdata[:qty * 2]
			# Set the connection status.
			self._ConnectStatus = 'running'
			self._AddCmdStatus(cmdname, 'ok')
		# This was a write and the response was an ack or nak.
		elif (cmd in (11, 13, 14)) and (telegramattr == 2):
			# Decode the ack/nak
			acknak = ModbusDataLib.BinStr2SignedInt(recvdata)
			# The Ack was OK. 
			if acknak != 0:
				self._ConnectStatus = 'faulted'
				self._AddCmdStatus(cmdname, 'deviceerr')
			else:
				# Set the connection status.
				self._ConnectStatus = 'running'
				self._AddCmdStatus(cmdname, 'ok')
		else:
			self._ConnectStatus = 'faulted'
			self._AddCmdStatus(cmdname, 'deviceerr')


		return self._WriteTable, nextpoll
Ejemplo n.º 16
0
    def GetFlagsBool(self, addr):
        """Read flags from the host (command 2).
		addr (integer) = SBus flags address.
		"""
        return ModbusDataLib.bin2boollist(self._SBusRequest(2, addr, 1,
                                                            None))[0]
Ejemplo n.º 17
0
    def GetDiscreteInputsBool(self, addr):
        """Read discrete inputs from the host (function 2).
		addr (integer) = Modbus discrete inputs address.
		"""
        return ModbusDataLib.bin2boollist(self._ModbusRequest(
            2, addr, 1, None))[0]
Ejemplo n.º 18
0
    def GetOutputsBool(self, addr):
        """Read outputs from the host (command 5).
		addr (integer) = SBus outputs address.
		"""
        return ModbusDataLib.bin2boollist(self._SBusRequest(5, addr, 1,
                                                            None))[0]
Ejemplo n.º 19
0
    def GetCoilsBool(self, addr):
        """Read coils from the host (function 1).
		addr (integer) = Modbus coil address.
		"""
        return ModbusDataLib.bin2boollist(self._ModbusRequest(
            1, addr, 1, None))[0]