main.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. # -*- coding: utf-8 -*-
  2. #
  3. # AWL simulator - PyProfibus hardware interface
  4. #
  5. # Copyright 2013-2017 Michael Buesch <m@bues.ch>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. from __future__ import division, absolute_import, print_function, unicode_literals
  22. #from awlsim.common.cython_support cimport * #@cy
  23. from awlsim.common.compat import *
  24. from awlsim.common.util import *
  25. from awlsim.common.exceptions import *
  26. #from awlsimhw_pyprofibus.main cimport * #@cy
  27. from awlsim.core.hardware_params import *
  28. from awlsim.core.hardware import * #+cimport
  29. from awlsim.core.operators import * #+cimport
  30. from awlsim.core.offset import * #+cimport
  31. from awlsim.core.cpu import * #+cimport
  32. class HardwareInterface_PyProfibus(AbstractHardwareInterface): #+cdef
  33. name = "PyProfibus"
  34. description = "PROFIBUS-DP support with PyProfibus.\n"\
  35. "https://bues.ch/a/profibus"
  36. # Hardware-specific parameters
  37. paramDescs = [
  38. HwParamDesc_str("config",
  39. defaultValue = "awlsimhw_pyprofibus.conf",
  40. description = "Awlsim pyprofibus module config file."),
  41. ]
  42. def __init__(self, sim, parameters={}):
  43. AbstractHardwareInterface.__init__(self,
  44. sim = sim,
  45. parameters = parameters)
  46. def __setupSlaves(self):
  47. setPrmReq = self.pyprofibus.dp.DpTelegram_SetPrm_Req
  48. dp1PrmMask = bytearray((setPrmReq.DPV1PRM0_FAILSAFE,
  49. setPrmReq.DPV1PRM1_REDCFG,
  50. 0x00))
  51. dp1PrmSet = bytearray((setPrmReq.DPV1PRM0_FAILSAFE,
  52. setPrmReq.DPV1PRM1_REDCFG,
  53. 0x00))
  54. for slaveConf in self.__conf.slaveConfs:
  55. desc = self.pyprofibus.DpSlaveDesc(
  56. identNumber = slaveConf.gsd.getIdentNumber(),
  57. slaveAddr = slaveConf.addr)
  58. desc.setCfgDataElements(slaveConf.gsd.getCfgDataElements())
  59. if slaveConf.gsd.isDPV1():
  60. desc.setUserPrmData(slaveConf.gsd.getUserPrmData(
  61. dp1PrmMask = dp1PrmMask,
  62. dp1PrmSet = dp1PrmSet))
  63. else:
  64. desc.setUserPrmData(slaveConf.gsd.getUserPrmData())
  65. desc.setSyncMode(bool(slaveConf.syncMode))
  66. desc.setFreezeMode(bool(slaveConf.freezeMode))
  67. desc.setGroupMask(int(slaveConf.groupMask))
  68. desc.setWatchdog(int(slaveConf.watchdogMs))
  69. desc._awlsimSlaveConf = slaveConf
  70. self.master.addSlave(desc)
  71. def __cleanup(self):
  72. if self.master:
  73. self.master.destroy()
  74. self.master = None
  75. self.phy = None
  76. self.cachedInputs = []
  77. def doStartup(self):
  78. # Import the PROFIBUS hardware access modules
  79. # and keep references to it.
  80. try:
  81. import pyprofibus
  82. import pyprofibus.phy_serial, pyprofibus.phy_dummy
  83. self.pyprofibus = pyprofibus
  84. except (ImportError, RuntimeError) as e:
  85. self.raiseException("Failed to import PROFIBUS protocol stack "
  86. "module 'pyprofibus':\n%s" % str(e))
  87. # Initialize the DPM
  88. self.phy = None
  89. self.master = None
  90. try:
  91. self.__conf = self.pyprofibus.PbConf.fromFile(
  92. self.getParamValueByName("config"))
  93. phyType = self.__conf.phyType.lower().strip()
  94. if phyType == "serial":
  95. self.phy = self.pyprofibus.phy_serial.CpPhySerial(
  96. debug = (self.__conf.debug >= 2),
  97. port = self.__conf.phyDev)
  98. elif phyType == "dummy_slave":
  99. self.phy = self.pyprofibus.phy_dummy.CpPhyDummySlave(
  100. debug = (self.__conf.debug >= 2))
  101. else:
  102. self.raiseException("Invalid phyType parameter value")
  103. self.phy.setConfig(baudrate = self.__conf.phyBaud)
  104. if self.__conf.dpMasterClass == 1:
  105. DPM_cls = self.pyprofibus.DPM1
  106. else:
  107. DPM_cls = self.pyprofibus.DPM2
  108. self.master = DPM_cls(phy = self.phy,
  109. masterAddr = self.__conf.dpMasterAddr,
  110. debug = (self.__conf.debug >= 1))
  111. self.__setupSlaves()
  112. self.master.initialize()
  113. self.slaveList = self.master.getSlaveList()
  114. self.cachedInputs = [None] * len(self.slaveList)
  115. except self.pyprofibus.PhyError as e:
  116. self.raiseException("Profibus-PHY error: %s" % str(e))
  117. self.__cleanup()
  118. except self.pyprofibus.DpError as e:
  119. self.raiseException("Profibus-DP error: %s" % str(e))
  120. self.__cleanup()
  121. except self.pyprofibus.FdlError as e:
  122. self.raiseException("Profibus-FDL error: %s" % str(e))
  123. self.__cleanup()
  124. except self.pyprofibus.conf.PbConfError as e:
  125. self.raiseException("Profibus configuration error: %s" % str(e))
  126. self.__cleanup()
  127. def doShutdown(self):
  128. self.__cleanup()
  129. def readInputs(self): #+cdef
  130. address = self.inputAddressBase
  131. for slave in self.slaveList:
  132. # Get the cached slave-data
  133. if not self.cachedInputs:
  134. break
  135. inputSize = slave._awlsimSlaveConf.inputSize
  136. inData = self.cachedInputs.pop(0)
  137. if not inData:
  138. continue
  139. inData = bytearray(inData)
  140. if len(inData) > inputSize:
  141. inData = inData[0:inputSize]
  142. if len(inData) < inputSize:
  143. inData += b'\0' * (inputSize - len(inData))
  144. self.sim.cpu.storeInputRange(address, inData)
  145. # Adjust the address base for the next slave.
  146. address += inputSize
  147. assert(not self.cachedInputs)
  148. def writeOutputs(self): #+cdef
  149. try:
  150. address = self.outputAddressBase
  151. for slave in self.slaveList:
  152. # Get the output data from the CPU
  153. outputSize = slave._awlsimSlaveConf.outputSize
  154. outData = self.sim.cpu.fetchOutputRange(address,
  155. outputSize)
  156. # Send it to the slave and request the input data.
  157. inData = self.master.runSlave(slave, outData)
  158. # Cache the input data for the readInputs() call.
  159. self.cachedInputs.append(inData)
  160. # Adjust the address base for the next slave.
  161. address += outputSize
  162. except self.pyprofibus.ProfibusError as e:
  163. self.raiseException("Hardware error: %s" % str(e))
  164. def directReadInput(self, accessWidth, accessOffset): #@nocy
  165. #@cy cdef bytearray directReadInput(self, uint32_t accessWidth, uint32_t accessOffset):
  166. return bytearray()#TODO
  167. def directWriteOutput(self, accessWidth, accessOffset, data): #@nocy
  168. #@cy cdef ExBool_t directWriteOutput(self, uint32_t accessWidth, uint32_t accessOffset, bytearray data) except ExBool_val:
  169. return False#TODO
  170. # Module entry point
  171. HardwareInterface = HardwareInterface_PyProfibus