__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. #!/usr/bin/env python3.5
  2. # Copyright 2017 Digital
  3. #
  4. # This file is part of DigiLib.
  5. #
  6. # DigiLib is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # DigiLib is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with DigiLib. If not, see <http://www.gnu.org/licenses/>.
  18. # Python modules
  19. import atexit
  20. import logging
  21. import threading
  22. import traceback
  23. # Third party modules
  24. import blinker
  25. import curio
  26. import digilib.network
  27. import digilib.misc
  28. log = logging.getLogger(__name__+"")
  29. lgpio = logging.getLogger(__name__+".gpio")
  30. # Error messages
  31. ERROR_TAKES_ARGUMENTS = "{} takes {} {} argument(s): {}"
  32. # respond(ERROR_TAKES_ARGUMENTS.format(
  33. # command, "one", "positional", "<name>"))
  34. _pins_for_cleanup = set()
  35. _gpio = None
  36. class GPIOWrapper(object):
  37. gpio = None
  38. OUT = "out"
  39. IN = "in"
  40. # BCM = "broadcom"
  41. pin_values = {}
  42. def __init__(self):
  43. super(GPIOWrapper,self).__init__()
  44. self.load_rpi_gpio()
  45. lgpio.debug("setting pin numbering to broadcom")
  46. if self.gpio:
  47. self.gpio.setmode(self.gpio.BCM)
  48. atexit.register(self.cleanup)
  49. def cleanup(self,*args):
  50. lgpio.debug("cleanup! ({})".format(args))
  51. if self.gpio:
  52. # gpio.cleanup wants a list or tuple, but _pins_for_cleanup is
  53. # a set. we have to convert it first.
  54. self.gpio.cleanup(list(_pins_for_cleanup))
  55. def load_rpi_gpio(self):
  56. try:
  57. self.gpio = False
  58. self.gpio = __import__("RPi.GPIO",fromlist="GPIO")
  59. except ImportError as e:
  60. lgpio.debug("failed to import RPi.GPIO")
  61. print("134")
  62. except Exception as e:
  63. lgpio.debug("unknown error occured", exc_info=e)
  64. print("137")
  65. finally:
  66. self.OUT = getattr(self.gpio,"OUT",self.OUT)
  67. self.IN = getattr(self.gpio,"IN",self.IN)
  68. # self.BCM = getattr(self.gpio,self.BCM)
  69. def output(self,pins,state,*args):
  70. lgpio.debug("setting pin(s) {} to value {}".format(
  71. pins,state))
  72. if type(pins) is int:
  73. pins = [pins]
  74. _pins_for_cleanup.update(pins)
  75. if self.gpio:
  76. self.gpio.output(pins,state)
  77. def input(self,pins,*args):
  78. values = []
  79. for p in pins:
  80. if self.gpio:
  81. values.append(self.gpio.input(p))
  82. else:
  83. values.append(-1)
  84. lgpio.debug("reading pins {}: {}".format(
  85. pins,values))
  86. return values
  87. def setup(self,pins,value,*args):
  88. lgpio.debug("setting pin(s) {} to {}".format(pins,value))
  89. if self.gpio:
  90. self.gpio.setup(pins,value)
  91. _gpio = GPIOWrapper()
  92. class PinBase(object):
  93. """PinBase is the base class for all classes representing a gpio pin"""
  94. pin_number = None
  95. value = None
  96. def __init__(self,pin_number,mode):
  97. super(PinBase,self).__init__()
  98. self.pin_number = pin_number
  99. self.value = self.value_low
  100. _gpio.setup(self.pin_number,_gpio.OUT)
  101. def output(self,value):
  102. [value] = digilib.misc.parse_to_int_list(value)
  103. self.value = value
  104. _gpio.output(self.pin_number,value)
  105. def input(self):
  106. value = _gpio.input(self.pin_number,value)
  107. return value
  108. class DigitalPin(PinBase):
  109. value_high = True
  110. value_low = False
  111. def __init__(self,pin_number,mode):
  112. super(DigitalPin,self).__init__(pin_number,mode)
  113. class AnalogPin(PinBase):
  114. value_high = 1
  115. value_low = 0
  116. def __init__(self,pin_number):
  117. super(AnalogPin,self).__init__(pin_number)
  118. class PinControllerBase(object):
  119. """docstring for PinControllerBase.
  120. PinControllerBase is the base class for all classes controlling one or more physical devices connected to a gpio header
  121. """
  122. pins = []
  123. def __init__(self,pins):
  124. super(PinControllerBase, self).__init__()
  125. self.pins.extend(pins)
  126. # def make_digital_pin(self,*args):
  127. # return DigitalPin(*args)
  128. # def make_analog_pin(self,*args):
  129. # return AnalogPin(*args)
  130. class PinAPIBase(object):
  131. """docstring for PinAPI.
  132. PinAPIBase is the base class for all classes providing an api to multiple
  133. PinController.
  134. """
  135. controllers = []
  136. def __init__(self):
  137. super(PinAPIBase, self).__init__()
  138. class PCEngine(PinControllerBase):
  139. """Test Class"""
  140. max_speed=1
  141. speed = 0
  142. turn_on_speed = 1
  143. is_on = False
  144. def __init__(self,pin_on_off,pin_analog):
  145. super(PCEngine, self).__init__([pin_on_off,pin_analog])
  146. # self.pins.append(pin_on_off)
  147. # self.pins.append(pin_analog)
  148. self.pin_on_off = DigitalPin(pin_on_off,_gpio.OUT)
  149. self.pin_analog = DigitalPin(pin_analog,_gpio.OUT)
  150. # self.pins.append(self.pin_on_off)
  151. # self.pins.append(self.pin_analog)
  152. # gpio.setup(self.pins,_gpio.OUT)
  153. # gpio.setup(self.pin_analog,_gpio.OUT)
  154. self.set_speed(1)
  155. self.set_state(1)
  156. def set_speed(self,speed):
  157. self.pin_analog.output(speed)
  158. self.speed = speed
  159. def set_state(self,state):
  160. """state is integer and specifies if the engine should be turned on (1) or turned off (0) """
  161. if state == self.is_on:
  162. return
  163. # self.set_speed(speed)
  164. self.pin_on_off.output(state)
  165. self.is_on = state
  166. class EnginesController(PinAPIBase):
  167. engine_left = None
  168. engine_right = None
  169. action_in_process = False
  170. def __init__(self,left,right):
  171. super(EnginesController,self).__init__()
  172. self.engine_right = self.make_engine(*right)
  173. self.engine_left = self.make_engine(*left)
  174. def make_engine(self,*args):
  175. return digilib.pin.PCEngine(*args)
  176. def set_engine_state(self,args=[],command=None,respond=None):
  177. if len(args) != 2:
  178. respond("missing argument(s): <engine> <state>")
  179. return
  180. [engine,state] = args
  181. if engine == "right":
  182. self.engine_right.set_state(state)
  183. elif engine == "left":
  184. self.engine_left.set_state(state)
  185. else:
  186. respond("unknown engine. use 'left' or 'right'")
  187. def set_engine_speed(self,args=[],command=None,respond=None):
  188. if len(args) != 2:
  189. respond("missing argument(s): <engine> <speed>")
  190. return
  191. [engine,speed] = args
  192. if engine == "right":
  193. self.engine_right.set_speed(speed)
  194. elif engine == "left":
  195. self.engine_left.set_speed(speed)
  196. else:
  197. respond("unknown engine. use 'left' or 'right'")
  198. async def turn(self,args=[],command=None,respond=None):
  199. if len(args) != 1:
  200. respond("one missing argument: direction")
  201. return
  202. [direction] = args
  203. # lgpio.debug(threading.current_thread())
  204. # with self ad
  205. lgpio.info("turning {}".format(direction))
  206. right_state = self.engine_right.is_on
  207. right_speed = self.engine_right.speed
  208. left_state = self.engine_left.is_on
  209. left_speed = self.engine_left.speed
  210. if direction == "right":
  211. self.engine_right.set_state(False)
  212. self.engine_left.set_state(True)
  213. self.engine_left.set_speed(1)
  214. elif direction == "left":
  215. self.engine_right.set_state(True)
  216. self.engine_right.set_speed(1)
  217. self.engine_left.set_state(False)
  218. await curio.sleep(2)
  219. # time.sleep(2)
  220. self.engine_right.set_state(right_state)
  221. self.engine_right.set_speed(right_speed)
  222. self.engine_left.set_state(left_state)
  223. self.engine_left.set_speed(left_speed)
  224. lgpio.info("done turning {}".format(direction))
  225. # set engines to previous values
  226. class LED(DigitalPin):
  227. def __init__(self,pin):
  228. super(DigitalPin,self).__init__(pin,_gpio.OUT)
  229. self.on()
  230. def on(self,args=[],command=None,respond=None):
  231. self.output(True)
  232. def off(self,args=[],command=None,respond=None):
  233. self.output(False)
  234. def set(self,args=[],command=None,respond=None):
  235. if len(args) != 1:
  236. respond("one missing argument: state")
  237. return
  238. [state] = args
  239. self.output(state)
  240. class StatusLED(PinControllerBase):
  241. def __init__(self,pin_red,pin_green):
  242. super(StatusLED,self).__init__([pin_red,pin_green])
  243. self.pin_red = DigitalPin(pin_red,_gpio.OUT)
  244. self.pin_green = DigitalPin(pin_green,_gpio.OUT)
  245. self.green()
  246. def red(self,args=[],command=None,respond=None):
  247. if len(args) > 1:
  248. respond(ERROR_TAKES_ARGUMENTS.format(
  249. command,"one","optional","<state>"))
  250. return
  251. elif len(args) == 1:
  252. state = digilib.misc.parse_to_int_list(*args)
  253. else:
  254. state = 1
  255. self.pin_red.output(state)
  256. self.pin_green.output(int(not state))
  257. def green(self,args=[],command=None,respond=None):
  258. if len(args) > 1:
  259. respond(ERROR_TAKES_ARGUMENTS.format(
  260. command,"one","optional","<state>"))
  261. return
  262. elif len(args) == 1:
  263. state = int(*args)
  264. else:
  265. state = 1
  266. self.pin_green.output(state)
  267. self.pin_red.output(int(not state))
  268. class DebugPinController(PinControllerBase):
  269. def output(self,args=[],command=None,respond=None):
  270. if len(args) != 2:
  271. respond(ERROR_TAKES_ARGUMENTS.format(
  272. command, "two", "positional", "<name>"))
  273. return False
  274. pins = digilib.misc.parse_to_int_list(args[0])
  275. [state] = digilib.misc.parse_to_int_list(args[1])
  276. _gpio.output(pins,state)
  277. def input(self,args=[],command=None,respond=None):
  278. if len(args) != 2:
  279. respond(ERROR_TAKES_ARGUMENTS.format(
  280. command, "two", "positional", "<name>"))
  281. return False
  282. pins = digilib.misc.parse_to_int_list(args[0])
  283. [state] = digilib.misc.parse_to_int_list(args[1])
  284. rv = _gpio.input(pins,state)
  285. lgpio.debug(rv)
  286. respond(str(rv))
  287. def raise_exc(self,args=[],command=None,respond=None):
  288. raise Exception("Test Exception")
  289. async def araise_exc(self,args=[],command=None,respond=None):
  290. state = digilib.misc.parse_to_int_list("1,2,3,4")
  291. a = 1+2
  292. raise Exception("Test Async Exception")
  293. if __name__ == "__main__":
  294. pass
  295. #