summaryrefslogtreecommitdiffstats
path: root/awlsimhw_pyprofibus/main.py
blob: 48f804e1a64aabae4b32656075f653f098292ddc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# -*- coding: utf-8 -*-
#
# AWL simulator - PyProfibus hardware interface
#
# Copyright 2013 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from awlsim.hardware import *
from awlsim.util import *


class HardwareInterface(AbstractHardwareInterface):
	name = "PyProfibus"

	# Hardware-specific parameters
	paramDescs = [
		HwParamDesc_int("debug",
				minValue = 0,
				description = "Debug level."),
		HwParamDesc_int("baud",
				defaultValue = 19200,
				minValue = 9600, maxValue = 12000000,
				description = "The PROFIBUS baud rate."),
		HwParamDesc_int("masterClass",
				defaultValue = 1,
				minValue = 1, maxValue = 2,
				description = "The DP-Master class."),
		HwParamDesc_int("masterAddr",
				defaultValue = 1,
				minValue = 0, maxValue = 126,
				description = "The DP-Address of the master."),
		HwParamDesc_int("spiDev",
				minValue = 0,
				description = "The SPI device number."),
		HwParamDesc_int("spiChip",
				minValue = 0,
				description = "The SPI device chip-select number."),
	]

	def __init__(self, sim, parameters={}):
		AbstractHardwareInterface.__init__(self,
						   sim = sim,
						   parameters = parameters)

	def __setupSlaves(self):
		#TODO: Rewrite. Must be configurable.
		et200s = self.DPM.DpSlaveDesc(identNumber = 0x806A,
					      slaveAddr = 8,
					      inputAddressRangeSize = 1,
					      outputAddressRangeSize = 2)
		for elem in (self.DP.DpCfgDataElement(0),
			     self.DP.DpCfgDataElement(0x20),
			     self.DP.DpCfgDataElement(0x20),
			     self.DP.DpCfgDataElement(0x10)):
			et200s.chkCfgTelegram.addCfgDataElement(elem)
		et200s.setPrmTelegram.addUserPrmData([0x11 | 0x40])
		et200s.setSyncMode(True)
		et200s.setFreezeMode(True)
		et200s.setGroupMask(1)
		et200s.setWatchdog(5000)
		self.master.addSlave(et200s)

	def __cleanup(self):
		if self.master:
			self.master.destroy()
		self.master = None
		self.phy = None
		self.cachedInputs = []

	def doStartup(self):
		# Import the PROFIBUS hardware access modules
		# and keep references to it.
		try:
			import pyprofibus.dp_master
			import pyprofibus.dp
			import pyprofibus.fdl
			import pyprofibus.phy
			self.DPM = pyprofibus.dp_master
			self.DP = pyprofibus.dp
			self.FDL = pyprofibus.fdl
			self.PHY = pyprofibus.phy
		except (ImportError, RuntimeError) as e:
			self.raiseException("Failed to import PROFIBUS protocol stack "
				"module 'pyprofibus':\n%s" % str(e))

		# Initialize the DPM
		self.phy = None
		self.master = None
		try:
			self.phy = self.PHY.CpPhy(device = self.getParam("spiDev"),
						  chipselect = self.getParam("spiChip"),
						  debug = True if (self.getParam("debug") >= 2) else False)
			self.phy.profibusSetPhyConfig(baudrate = self.getParam("baud"))
			if self.getParam("masterClass") == 1:
				DPM_cls = self.DPM.DPM1
			else:
				DPM_cls = self.DPM.DPM2
			self.master = DPM_cls(phy = self.phy,
					      masterAddr = self.getParam("masterAddr"),
					      debug = True if (self.getParam("debug") >= 1) else False)
			self.__setupSlaves()
			self.master.initialize()
			self.slaveList = self.master.getSlaveList()
			self.cachedInputs = [None] * len(self.slaveList)
		except self.PHY.PhyError as e:
			self.raiseException("PHY error: %s" % str(e))
			self.__cleanup()
		except self.DP.DpError as e:
			self.raiseException("Profibus-DP error: %s" % str(e))
			self.__cleanup()
		except self.FDL.FdlError as e:
			self.raiseException("Fieldbug Data Link error: %s" % str(e))
			self.__cleanup()

	def doShutdown(self):
		self.__cleanup()

	def readInputs(self):
		address = self.inputAddressBase
		for slave in self.slaveList:
			# Get the cached slave-data
			inData = self.cachedInputs.pop(0)
			if not inData:
				continue
			if len(inData) != slave.inputAddressRangeSize:
				self.raiseException("Input data from slave '%s' has "
					"invalid length %d (expected %d)" %\
					(str(slave), len(inData),
					 slave.inputAddressRangeSize))
			self.sim.cpu.storeInputRange(address, inData)
			# Adjust the address base for the next slave.
			address += slave.inputAddressRangeSize
		assert(not self.cachedInputs)

	def writeOutputs(self):
		try:
			address = self.outputAddressBase
			for slave in self.slaveList:
				# Get the output data from the CPU
				outData = self.sim.cpu.fetchOutputRange(address,
						slave.outputAddressRangeSize)
				# Send it to the slave and request the input data.
				inData = self.master.dataExchange(slave.slaveAddr,
								  outData)
				# Cache the input data for the readInputs() call.
				self.cachedInputs.append(inData)
				# Adjust the address base for the next slave.
				address += slave.outputAddressRangeSize
		except (self.PHY.PhyError, self.DP.DpError, self.FDL.FdlError) as e:
			self.raiseException("Hardware error: %s" % str(e))

	def directReadInput(self, accessWidth, accessOffset):
		return None#TODO

	def directWriteOutput(self, accessWidth, accessOffset, data):
		return False#TODO
bues.ch cgit interface