hal.py
1 #!/usr/bin/env python 2 # vim: sts=4 sw=4 et 3 4 """ 5 6 This module allows the creation of userspace HAL components in Python. 7 This includes pins and parameters of the various HAL types. 8 9 Typical usage: 10 11 import hal, time 12 h = hal.component("component-name") 13 # create pins and parameters with calls to h.newpin and h.newparam 14 h.newpin("in", hal.HAL_FLOAT, hal.HAL_IN) 15 h.newpin("out", hal.HAL_FLOAT, hal.HAL_OUT) 16 h.ready() # mark the component as 'ready' 17 18 try: 19 while 1: 20 # act on changed input pins; update values on output pins 21 time.sleep(1) 22 h['out'] = h['in'] 23 except KeyboardInterrupt: pass 24 25 26 When the component is requested to exit with 'halcmd unload', a 27 KeyboardInterrupt exception will be raised. 28 """ 29 30 import _hal 31 from _hal import * 32 33 class _ItemWrap(object): 34 def __new__(cls, item): 35 if not isinstance(item, _hal.item): 36 raise TypeError("Constructor argument must be _hal.item: %s" % type(item)) 37 self = super(_ItemWrap, cls).__new__(cls) 38 return self._item_wrap(item) 39 40 def _item_wrap(self, item): 41 for f in ['get', 'set', 'get_type', 'get_name', 'get_dir', 'is_pin', '__repr__']: 42 setattr(self, f, getattr(item, f)) 43 return self 44 45 def __init__(self, item): 46 self._item = item 47 48 name = property(lambda s: s._item.get_name()) 49 type = property(lambda s: s._item.get_type()) 50 dir = property(lambda s: s._item.get_dir()) 51 52 value = property(lambda s: s._item.get(), lambda s,v: s._item.set(v)) 53 54 class Pin(_ItemWrap): 55 def __init__(self, item): 56 _ItemWrap.__init__(self, item) 57 if not item.is_pin(): 58 raise TypeError("Must be constructed from pin object") 59 60 class Param(_ItemWrap): 61 def __init__(self, item): 62 _ItemWrap.__init__(self, item) 63 if item.is_pin(): 64 raise TypeError("Must be constructed from param object") 65 66 class component(_hal.component): 67 def newpin(self, *a, **kw): return Pin(_hal.component.newpin(self, *a, **kw)) 68 def newparam(self, *a, **kw): return Param(_hal.component.newparam(self, *a, **kw)) 69 70 def getpin(self, *a, **kw): return Pin(_hal.component.getpin(self, *a, **kw)) 71 def getparam(self, *a, **kw): return Param(_hal.component.getparam(self, *a, **kw))