main.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # -*- coding: utf-8 -*-
  2. #
  3. # AWL simulator - Raspberry Pi GPIO hardware interface
  4. #
  5. # Copyright 2016 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.compat import *
  23. from awlsim.core.hardware import *
  24. from awlsim.core.operators import AwlOperator
  25. from awlsim.core.datatypes import AwlOffset
  26. import re
  27. class HwParamDesc_IOMap(HwParamDesc):
  28. typeStr = "BCM-port-number"
  29. _valueRe = re.compile(r'^\s*(?:BCM)?(\d+)\s*$')
  30. def __init__(self, mem):
  31. HwParamDesc.__init__(self,
  32. name = "%s0.0" % mem,
  33. description = "Example: %s1.4=BCM26" % mem)
  34. def parse(self, value):
  35. try:
  36. if not value:
  37. raise ValueError
  38. m = self._valueRe.match(value.upper())
  39. if not m:
  40. raise ValueError
  41. bcm = int(m.group(1), 10)
  42. if bcm < 0:
  43. raise ValueError
  44. return bcm
  45. except ValueError:
  46. raise self.ParseError("Invalid BCM port number: %s" % value)
  47. def match(self, matchName):
  48. if not matchName:
  49. return False
  50. return bool(self._nameRe.match(matchName))
  51. class HwParamDesc_IMap(HwParamDesc_IOMap):
  52. _nameRe = re.compile(r'^\s*[EI]([0-9]+)\.([0-7])\s*$')
  53. def __init__(self):
  54. HwParamDesc_IOMap.__init__(self, mem = "I")
  55. class HwParamDesc_QMap(HwParamDesc_IOMap):
  56. _nameRe = re.compile(r'^\s*[AQ]([0-9])+\.([0-7])\s*$')
  57. def __init__(self):
  58. HwParamDesc_IOMap.__init__(self, mem = "Q")
  59. class RpiGPIO_BitMapping(object):
  60. """Awlsim -> RaspiGPIO memory bit mapping.
  61. """
  62. def __init__(self):
  63. # Bit number to BCM GPIO number map.
  64. self.bit2bcm = [ None, ] * 8
  65. self.mapList = []
  66. def setBit(self, bitOffset, bcmNumber):
  67. assert(bitOffset >= 0 and bitOffset <= 7)
  68. self.bit2bcm[bitOffset] = bcmNumber
  69. def build(self):
  70. self.mapList = [ (bitOffset, self.bit2bcm[bitOffset])
  71. for bitOffset in range(8)
  72. if self.bit2bcm[bitOffset] is not None ]
  73. def __repr__(self):
  74. return "{ " +\
  75. ", ".join("%d: %s" % (i, str(self.bit2bcm[i]))
  76. for i in range(8)) +\
  77. " }"
  78. class RpiGPIO_HwInterface(AbstractHardwareInterface):
  79. """Raspberry Pi GPIO hardware interface.
  80. """
  81. name = "RPi.GPIO"
  82. paramDescs = [
  83. HwParamDesc_IMap(),
  84. HwParamDesc_QMap(),
  85. ]
  86. def __init__(self, sim, parameters={}):
  87. AbstractHardwareInterface.__init__(self,
  88. sim = sim,
  89. parameters = parameters)
  90. def doStartup(self):
  91. """Startup the hardware module.
  92. """
  93. # Get the configuration
  94. inputs = self.getParamsByDescType(HwParamDesc_IMap)
  95. outputs = self.getParamsByDescType(HwParamDesc_QMap)
  96. # Import the Raspberry Pi GPIO module
  97. try:
  98. import RPi.GPIO as RPi_GPIO
  99. self.__RPi_GPIO = RPi_GPIO
  100. except ImportError as e:
  101. self.raiseException("Failed to import Raspberry Pi GPIO "
  102. "module 'RPi.GPIO': %s" % str(e))
  103. # Initialize the GPIO library
  104. try:
  105. RPi_GPIO.setmode(self.__RPi_GPIO.BCM)
  106. RPi_GPIO.setwarnings(False)
  107. except RuntimeError as e:
  108. self.raiseException("Failed to init Raspberry Pi "
  109. "GPIO library: %s" % str(e))
  110. # Build the memory mappings
  111. self.__inputMap, self.__inputList = self.__mapGPIO(
  112. inputs, HwParamDesc_IMap._nameRe, RPi_GPIO.IN,
  113. self.inputAddressBase)
  114. self.__outputMap, self.__outputList = self.__mapGPIO(
  115. outputs, HwParamDesc_QMap._nameRe, RPi_GPIO.OUT,
  116. self.outputAddressBase)
  117. def __mapGPIO(self, configs, nameRegEx, gpioDir, byteBaseOffset):
  118. mapDict = {}
  119. RPi_GPIO = self.__RPi_GPIO
  120. for address, bcmNumber in configs:
  121. m = nameRegEx.match(address)
  122. byteOffset = int(m.group(1), 10)
  123. bitOffset = int(m.group(2), 10)
  124. mapping = mapDict.setdefault(byteBaseOffset + byteOffset,
  125. RpiGPIO_BitMapping())
  126. mapping.setBit(bitOffset, bcmNumber)
  127. try:
  128. if gpioDir == RPi_GPIO.IN:
  129. RPi_GPIO.setup(bcmNumber,
  130. gpioDir,
  131. pull_up_down = RPi_GPIO.PUD_DOWN)
  132. else:
  133. RPi_GPIO.setup(bcmNumber,
  134. gpioDir,
  135. initial = RPi_GPIO.LOW)
  136. except RuntimeError as e:
  137. self.raiseException("Failed to init Raspberry Pi "
  138. "BCM%d: %s" % (bcmNumber, str(e)))
  139. for bitMapping in dictValues(mapDict):
  140. bitMapping.build()
  141. mapList = list(sorted(
  142. [ (byteOffset, bitMapping)
  143. for byteOffset, bitMapping in dictItems(mapDict) ],
  144. key = lambda _tuple: _tuple[0]
  145. ))
  146. return mapDict, mapList
  147. def doShutdown(self):
  148. pass # Do nothing
  149. def readInputs(self):
  150. RPi_GPIO = self.__RPi_GPIO
  151. for byteOffset, bitMapping in self.__inputList:
  152. inByte = 0
  153. for bitOffset, bcmNumber in bitMapping.mapList:
  154. if RPi_GPIO.input(bcmNumber):
  155. inByte |= 1 << bitOffset
  156. self.sim.cpu.storeInputRange(byteOffset, (inByte, ))
  157. def writeOutputs(self):
  158. RPi_GPIO = self.__RPi_GPIO
  159. for byteOffset, bitMapping in self.__outputList:
  160. outByte = self.sim.cpu.fetchOutputRange(byteOffset, 1)[0]
  161. for bitOffset, bcmNumber in bitMapping.mapList:
  162. RPi_GPIO.output(bcmNumber,
  163. outByte & (1 << bitOffset))
  164. def directReadInput(self, accessWidth, accessOffset):
  165. if accessOffset < self.inputAddressBase:
  166. return None
  167. RPi_GPIO = self.__RPi_GPIO
  168. nrBytes = accessWidth // 8
  169. pass#TODO
  170. return None
  171. def directWriteOutput(self, accessWidth, accessOffset, data):
  172. if accessOffset < self.outputAddressBase:
  173. return False
  174. RPi_GPIO = self.__RPi_GPIO
  175. nrBytes = accessWidth // 8
  176. pass#TODO
  177. return True
  178. # The main entry point to the module.
  179. HardwareInterface = RpiGPIO_HwInterface