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 from . import LOG as _LOG
20 from . import PyComediError as _PyComediError
22 from pycomedi cimport _comedilib_h
25 def raise_error(function_name=None, ret=None, error_msg=None):
26 """Report an error while executing a comedilib function
28 >>> from pycomedi import PyComediError
29 >>> raise_error(function_name='myfn', ret=-1)
30 Traceback (most recent call last):
32 PyComediError: myfn: Success (-1)
33 >>> raise_error(function_name='myfn', ret=-1, error_msg='some error')
34 Traceback (most recent call last):
36 PyComediError: myfn (some error): Success (-1)
38 ... raise_error(function_name='myfn', ret=-1)
39 ... except PyComediError as e:
40 ... print(e.function_name)
45 errno = _comedilib_h.comedi_errno()
46 comedi_msg = _comedilib_h.comedi_strerror(errno)
48 function_name=function_name, ret=ret, comedi_msg=comedi_msg,
52 def _comedi_getter(name, is_invalid):
53 # Hmm, cannot get function by name, or pass differing function pointers...
54 #def comedi_get(function_name, *args, **kwargs):
55 def comedi_get(function, *args, **kwargs):
56 #fn = getattr(_comedilib_h, function_name)
57 fn = function # workaround until I get getattr() working
58 function_name = function.__name__
59 if 'error_msg' in kwargs:
60 error_msg = kwargs.pop('error_msg')
62 error_msg = 'error while running %s with %s and %s' % (
63 function_name, args, kwargs)
65 _LOG.debug('calling %s with %s %s' % (function_name, args, kwargs))
67 ret = fn(*args, **kwargs)
68 _LOG.debug(' call to %s returned %s' % (function_name, ret))
71 error_msg=error_msg, function_name=function_name, ret=ret)
73 #comedi_get.__name__ = name
74 #comedi_get.__doc__ = (
75 # "Execute Comedilib's `<function_name>(*args, **kwargs)` safely.")
78 comedi_int = _comedi_getter('comedi_int', lambda ret: ret < 0)
79 comedi_ptr = _comedi_getter('comedi_ptr', lambda ret: ret == None)
80 comedi_tup = _comedi_getter('comedi_tup', lambda ret: ret[0] < 0)