1 # Copyright (C) 2011-2012 W. Trevor King <wking@tremily.us>
3 # This file is part of pycomedi.
5 # pycomedi is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 2 of the License, or (at your option) any later
10 # pycomedi is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License along with
15 # pycomedi. If not, see <http://www.gnu.org/licenses/>.
17 "Useful error checking wrappers around Comedilib function calls"
19 # No relative imports in Cython yet, see
20 # http://trac.cython.org/cython_trac/ticket/542
21 from pycomedi import LOG as _LOG
22 from pycomedi import PyComediError as _PyComediError
27 def raise_error(function_name=None, ret=None, error_msg=None):
28 """Report an error while executing a comedilib function
30 >>> from pycomedi import PyComediError
31 >>> raise_error(function_name='myfn', ret=-1)
32 Traceback (most recent call last):
34 PyComediError: myfn: Success (-1)
35 >>> raise_error(function_name='myfn', ret=-1, error_msg='some error')
36 Traceback (most recent call last):
38 PyComediError: myfn (some error): Success (-1)
40 ... raise_error(function_name='myfn', ret=-1)
41 ... except PyComediError, e:
42 ... print(e.function_name)
47 errno = _comedilib_h.comedi_errno()
48 comedi_msg = _comedilib_h.comedi_strerror(errno)
50 function_name=function_name, ret=ret, comedi_msg=comedi_msg,
54 def _comedi_getter(name, is_invalid):
55 # Hmm, cannot get function by name, or pass differing function pointers...
56 #def comedi_get(function_name, *args, **kwargs):
57 def comedi_get(function, *args, **kwargs):
58 #fn = getattr(_comedilib_h, function_name)
59 fn = function # workaround until I get getattr() working
60 function_name = function.__name__
61 if 'error_msg' in kwargs:
62 error_msg = kwargs.pop('error_msg')
64 error_msg = 'error while running %s with %s and %s' % (
65 function_name, args, kwargs)
67 _LOG.debug('calling %s with %s %s' % (function_name, args, kwargs))
69 ret = fn(*args, **kwargs)
70 _LOG.debug(' call to %s returned %s' % (function_name, ret))
73 error_msg=error_msg, function_name=function_name, ret=ret)
75 #comedi_get.__name__ = name
76 #comedi_get.__doc__ = (
77 # "Execute Comedilib's `<function_name>(*args, **kwargs)` safely.")
80 comedi_int = _comedi_getter('comedi_int', lambda ret: ret < 0)
81 comedi_ptr = _comedi_getter('comedi_ptr', lambda ret: ret == None)
82 comedi_tup = _comedi_getter('comedi_tup', lambda ret: ret[0] < 0)