summaryrefslogtreecommitdiffstats
path: root/awlsim/main.py
blob: 1d895b3fa0fcf3b96b123138c34dbfc52fd7b18e (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
# -*- coding: utf-8 -*-
#
# AWL simulator
#
# Copyright 2012-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.cpu import *
from awlsim.util import *
from awlsim.version import *
from awlsim.hardware import *

import importlib


class AwlSim(object):
	def __init__(self):
		self.__registeredHardware = []
		self.cpu = S7CPU(self)
		self.cpu.setPeripheralReadCallback(self.__peripheralReadCallback)
		self.cpu.setPeripheralWriteCallback(self.__peripheralWriteCallback)

	def __handleSimException(self, e):
		if not e.getCpu():
			# The CPU reference is not set, yet.
			# Set it to the current CPU.
			e.setCpu(self.cpu)
		raise e

	def shutdown(self):
		for hw in self.__registeredHardware:
			hw.shutdown()

	def load(self, parseTree):
		try:
			self.cpu.load(parseTree)
			for hw in self.__registeredHardware:
				hw.startup()
			self.cpu.startup()
		except AwlSimError as e:
			self.__handleSimException(e)

	def getCPU(self):
		return self.cpu

	def runCycle(self):
		try:
			for hw in self.__registeredHardware:
				hw.readInputs()
			self.cpu.runCycle()
			for hw in self.__registeredHardware:
				hw.writeOutputs()
		except AwlSimError as e:
			self.__handleSimException(e)

	def registerHardware(self, hwClassInst):
		"""Register a new hardware interface."""

		self.__registeredHardware.append(hwClassInst)

	def registerHardwareClass(self, hwClass, parameters={}):
		"""Register a new hardware interface class.
		'parameters' is a dict of hardware specific parameters.
		Returns the instance of the hardware class."""

		hwClassInst = hwClass(sim = self,
				      parameters = parameters)
		self.registerHardware(hwClassInst)
		return hwClassInst

	@classmethod
	def loadHardwareModule(cls, name):
		"""Load a hardware interface module.
		'name' is the name of the module to load (without 'awlsimhw_' prefix).
		Returns the HardwareInterface class."""

		# Construct the python module name
		moduleName = "awlsimhw_%s" % name
		# Try to import the module
		try:
			mod = importlib.import_module(moduleName)
		except ImportError as e:
			raise AwlSimError("Failed to import hardware interface "
				"module '%s' (import name '%s'): %s" %\
				(name, moduleName, str(e)))
		# Fetch and instantiate the interface object
		hwClassName = "HardwareInterface"
		hwClass = getattr(mod, hwClassName, None)
		if not hwClass:
			raise AwlSimError("Hardware module '%s' (import name '%s') "
				"does not have a '%s' class." %\
				(name, moduleName, hwClassName))
		return hwClass

	def __peripheralReadCallback(self, userData, width, offset):
		# The CPU issued a direct peripheral read access.
		# Poke all registered hardware modules, but only return the value
		# from the last module returning a valid value.

		retValue = None
		for hw in self.__registeredHardware:
			value = hw.directReadInput(width, offset)
			if value is not None:
				retValue = value
		return retValue

	def __peripheralWriteCallback(self, userData, width, offset, value):
		# The CPU issued a direct peripheral write access.
		# Send the write request down to all hardware modules.
		# Returns true, if any hardware accepted the value.

		retOk = False
		for hw in self.__registeredHardware:
			ok = hw.directWriteOutput(width, offset, value)
			if not retOk:
				retOk = ok
		return retOk

	def __repr__(self):
		return str(self.cpu)
bues.ch cgit interface