Skip to content

Commit

Permalink
All files compatible with Python 2 and Python 3 (remove 2to3)
Browse files Browse the repository at this point in the history
  • Loading branch information
clade committed Oct 18, 2021
1 parent 20b35fa commit b6d7791
Show file tree
Hide file tree
Showing 17 changed files with 438 additions and 437 deletions.
94 changes: 47 additions & 47 deletions PyDAQmx/DAQmxCallBack.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,47 @@
import weakref
import DAQmxConfig

""" This package import helper functions to pass data to call back functions
See examples
"""

#if DAQmxConfig.NIDAQmxBase:
# raise NotImplementedError, 'Call back function are not available with the NIDAQmxBase driver'

# NIDAQmx allow to pass a pointer to a data structure in callback function
# If this function is implemented in Python, we would like this data to be a Python object.
# This object will not (and will not) be used in C but we want to pass a reference to it.
# A workaround is to use the weakref module
#
# Define a weakref dictionnary to be able to remember objects and retrieve them by ID
_id2obj_dict = weakref.WeakValueDictionary()

def create_callbackdata_id(obj):
"""
Uses the weakref module to create and store a reference to obj
output value: reference to the object
It is not possible to directly uses python object through a Callback function because
with ctypes there is no pointer to python object.
This function store in a dictionary a reference to an object
This object can be retrieved using the get_callbackdata_from_id function
For python object that cannot be weakreferenced, one can creat a dummy class to wrap
the python object :
def MyList(list)
pass
data = MyList()
id = create_callbackdata_id(data)
"""
oid = id(obj)
_id2obj_dict[oid] = obj
return oid

def get_callbackdata_from_id(oid):
"""Retrieve an object stored using create_callbackdata_id
"""
return _id2obj_dict[oid]
import weakref
from . import DAQmxConfig

""" This package import helper functions to pass data to call back functions
See examples
"""

#if DAQmxConfig.NIDAQmxBase:
# raise NotImplementedError, 'Call back function are not available with the NIDAQmxBase driver'

# NIDAQmx allow to pass a pointer to a data structure in callback function
# If this function is implemented in Python, we would like this data to be a Python object.
# This object will not (and will not) be used in C but we want to pass a reference to it.
# A workaround is to use the weakref module
#
# Define a weakref dictionnary to be able to remember objects and retrieve them by ID
_id2obj_dict = weakref.WeakValueDictionary()

def create_callbackdata_id(obj):
"""
Uses the weakref module to create and store a reference to obj
output value: reference to the object
It is not possible to directly uses python object through a Callback function because
with ctypes there is no pointer to python object.
This function store in a dictionary a reference to an object
This object can be retrieved using the get_callbackdata_from_id function
For python object that cannot be weakreferenced, one can creat a dummy class to wrap
the python object :
def MyList(list)
pass
data = MyList()
id = create_callbackdata_id(data)
"""
oid = id(obj)
_id2obj_dict[oid] = obj
return oid

def get_callbackdata_from_id(oid):
"""Retrieve an object stored using create_callbackdata_id
"""
return _id2obj_dict[oid]
4 changes: 2 additions & 2 deletions PyDAQmx/DAQmxConfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def get_lib():
# If the DAQmxConfigTest has been imported, then uses the value from this file
# This can be used to try different version or compile the module on a plateform where
# DAQmx is not installed
if "DAQmxConfigTest" in sys.modules.keys():
if "DAQmxConfigTest" in list(sys.modules.keys()):
from DAQmxConfigTest import *
if lib_name is None:
def get_lib():
Expand All @@ -104,5 +104,5 @@ def __getattr__(self, name):
return DAQlib, DAQlib_variadic

if dot_h_file is None or not os.path.exists(dot_h_file):
raise NotImplementedError, "Location of niDAQmx library and include file unknown on %s - if you find out, please let the PyDAQmx project know" % (sys.platform)
raise NotImplementedError("Location of niDAQmx library and include file unknown on %s - if you find out, please let the PyDAQmx project know" % (sys.platform))

4 changes: 2 additions & 2 deletions PyDAQmx/DAQmxConstants.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"""

import re
from DAQmxConfig import dot_h_file
from .DAQmxConfig import dot_h_file

include_file = open(dot_h_file,'r') #Open NIDAQmx.h file

Expand All @@ -18,7 +18,7 @@

for copyright_line in preamble:
if "Copyright" in copyright_line:
DAQmx_copyright_year = max(map(int, re.findall('\d\d\d\d', copyright_line)))
DAQmx_copyright_year = max([int(elm) for elm in re.findall('\d\d\d\d', copyright_line)])
break
else:
DAQmx_copyright_year = 2003
Expand Down
8 changes: 4 additions & 4 deletions PyDAQmx/DAQmxFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
from ctypes import *
import warnings

import DAQmxConfig
from DAQmxTypes import *
from DAQmxConstants import constant_list
import DAQmxConstants
from . import DAQmxConfig
from .DAQmxTypes import *
from .DAQmxConstants import constant_list
from . import DAQmxConstants

class DAQException(Exception):
"""Exception raised from the NIDAQ.
Expand Down
2 changes: 1 addition & 1 deletion PyDAQmx/DAQmxTypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from ctypes import *
import ctypes
from DAQmxConstants import DAQmx_copyright_year
from .DAQmxConstants import DAQmx_copyright_year

# New types definitions
# Correspondance between the name used in the NiDAQmx.h file and ctypes
Expand Down
10 changes: 5 additions & 5 deletions PyDAQmx/Task.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from DAQmxTypes import TaskHandle
import DAQmxFunctions
from DAQmxFunctions import *
from .DAQmxTypes import TaskHandle
from . import DAQmxFunctions
from .DAQmxFunctions import *
import ctypes


Expand All @@ -17,7 +17,7 @@
task_function_list = [name for name in task_function_list if name not in ['DAQmxClearTask']]

try :
from DAQmxCallBack import *
from .DAQmxCallBack import *
_callback = True
except NotImplementedError:
_callback = False
Expand Down Expand Up @@ -98,7 +98,7 @@ def SignalCallback_py(taskHandle, signalID, self_id):
class CallbackParent(object):
def __getattr__(self, name):
if name in ['AutoRegisterEveryNSamplesEvent', 'AutoRegisterDoneEvent', 'AutoRegisterSignalEvent']:
raise NotImplementedError, 'Callback methods are not available'
raise NotImplementedError('Callback methods are not available')
return super(CallbackParent, self).__getattr__(name)


Expand Down
16 changes: 8 additions & 8 deletions PyDAQmx/__init__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# -*- coding: utf-8 -*-

import DAQmxConfig
from . import DAQmxConfig

from DAQmxTypes import *
from DAQmxConstants import *
from DAQmxFunctions import *
from Task import Task
from .DAQmxTypes import *
from .DAQmxConstants import *
from .DAQmxFunctions import *
from .Task import Task

import DAQmxConstants
import DAQmxFunctions
from . import DAQmxConstants
from . import DAQmxFunctions

all_types = ['int8', 'uInt8', 'int16', 'uInt16', 'int32', 'uInt32', 'float32', 'float64', 'int64', 'uInt64', 'bool32',
'TaskHandle', 'CalHandle', 'DAQmxEveryNSamplesEventCallbackPtr', 'DAQmxDoneEventCallbackPtr', 'DAQmxSignalEventCallbackPtr', 'CtypesString']
Expand All @@ -24,7 +24,7 @@
globals()[new_name] = globals()[name]

##### WARNING, version should also be modified in the setup.py
__version_info__ = (1, 4, 4)
__version_info__ = (1, 4, 5)
__version__ = '.'.join(str(num) for num in __version_info__)

__author__ =u'Pierre Cladé'
176 changes: 88 additions & 88 deletions PyDAQmx/example/AnalogInput_acq_IntClk.py
Original file line number Diff line number Diff line change
@@ -1,88 +1,88 @@
import PyDAQmx
from PyDAQmx import Task, DAQmxResetDevice, int32
from ctypes import byref
import numpy


class AIParameters(object):
limits = (-10, 10)
physicalChannel = ["/Dev1/ai0"]

def __init__(self, sample_rate, sample_number, channels=None, limits=None):
self.sampleRate = sample_rate
self.sampleNumber = sample_number
if limits is None:
limits = self.limits
self.limit_inf= limits[0]
self.limit_sup= limits[1]
if channels is not None:
if type(channels) is str:
physicalChannel = [channels]
self.physicalChannel = channels

@property
def device_name(self):
device_name = self.physicalChannel[0].split('/')[0]
if device_name == '' :
device_name = self.physicalChannel[0].split('/')[1]
return device_name

class Trigger(object):
def __init__(self, terminal):
self.terminal = terminal

class RisingTrigger(Trigger):
direction = PyDAQmx.DAQmx_Val_Rising

class FallingTrigger(Trigger):
direction = PyDAQmx.DAQmx_Val_Falling


class AIVoltageChan(Task):
def __init__(self, ai_param, reset=True, terminalConfig=PyDAQmx.DAQmx_Val_RSE, trigger=None):
if reset:
DAQmxResetDevice(ai_param.device_name)
super(AIVoltageChan, self).__init__()
self.sampleNumber = ai_param.sampleNumber
self.sampleRate = ai_param.sampleRate
self.limit_inf = ai_param.limit_inf
self.limit_sup = ai_param.limit_sup
self.physicalChannel = ai_param.physicalChannel
self.numberOfChannel = len(ai_param.physicalChannel)
if isinstance(terminalConfig, basestring):
terminalConfig = getattr(PyDAQmx, terminalConfig)
self.terminalConfig = terminalConfig
self.trigger = trigger
self.configure()
def configure(self):
channel_string = ','.join(self.physicalChannel)
self.CreateAIVoltageChan(channel_string,"",self.terminalConfig,
self.limit_inf,self.limit_sup,
PyDAQmx.DAQmx_Val_Volts,None)
def start(self):
n = self.sampleNumber
sampleRate = self.sampleRate
self.CfgSampClkTiming("",sampleRate,PyDAQmx.DAQmx_Val_Rising,PyDAQmx.DAQmx_Val_FiniteSamps,n)
if self.trigger is not None:
self.CfgDigEdgeRefTrig(self.trigger.terminal,self.trigger.direction,10)
self.StartTask()
def read(self):
n = self.sampleNumber
data = numpy.zeros((n,self.numberOfChannel), dtype=numpy.float64)
read = int32()
self.ReadAnalogF64(n,10.0,PyDAQmx.DAQmx_Val_GroupByScanNumber,data,n*self.numberOfChannel,byref(read),None)
return data
def stop(self):
self.StopTask()
def wait(self, timeout=10):
self.WaitUntilTaskDone(timeout)


if __name__=="__main__":
ai = AIVoltageChan(ai_param=AIParameters(100000, 10000, ['/dev1/ai0', '/dev1/ai1']),
terminalConfig="DAQmx_Val_PseudoDiff",
trigger=RisingTrigger('/dev1/PFI0'))
ai.start()
ai.wait()
ai.read()
ai.stop()
import PyDAQmx
from PyDAQmx import Task, DAQmxResetDevice, int32
from ctypes import byref
import numpy


class AIParameters(object):
limits = (-10, 10)
physicalChannel = ["/Dev1/ai0"]

def __init__(self, sample_rate, sample_number, channels=None, limits=None):
self.sampleRate = sample_rate
self.sampleNumber = sample_number
if limits is None:
limits = self.limits
self.limit_inf= limits[0]
self.limit_sup= limits[1]
if channels is not None:
if type(channels) is str:
physicalChannel = [channels]
self.physicalChannel = channels

@property
def device_name(self):
device_name = self.physicalChannel[0].split('/')[0]
if device_name == '' :
device_name = self.physicalChannel[0].split('/')[1]
return device_name

class Trigger(object):
def __init__(self, terminal):
self.terminal = terminal

class RisingTrigger(Trigger):
direction = PyDAQmx.DAQmx_Val_Rising

class FallingTrigger(Trigger):
direction = PyDAQmx.DAQmx_Val_Falling


class AIVoltageChan(Task):
def __init__(self, ai_param, reset=True, terminalConfig=PyDAQmx.DAQmx_Val_RSE, trigger=None):
if reset:
DAQmxResetDevice(ai_param.device_name)
super(AIVoltageChan, self).__init__()
self.sampleNumber = ai_param.sampleNumber
self.sampleRate = ai_param.sampleRate
self.limit_inf = ai_param.limit_inf
self.limit_sup = ai_param.limit_sup
self.physicalChannel = ai_param.physicalChannel
self.numberOfChannel = len(ai_param.physicalChannel)
if isinstance(terminalConfig, str):
terminalConfig = getattr(PyDAQmx, terminalConfig)
self.terminalConfig = terminalConfig
self.trigger = trigger
self.configure()
def configure(self):
channel_string = ','.join(self.physicalChannel)
self.CreateAIVoltageChan(channel_string,"",self.terminalConfig,
self.limit_inf,self.limit_sup,
PyDAQmx.DAQmx_Val_Volts,None)
def start(self):
n = self.sampleNumber
sampleRate = self.sampleRate
self.CfgSampClkTiming("",sampleRate,PyDAQmx.DAQmx_Val_Rising,PyDAQmx.DAQmx_Val_FiniteSamps,n)
if self.trigger is not None:
self.CfgDigEdgeRefTrig(self.trigger.terminal,self.trigger.direction,10)
self.StartTask()
def read(self):
n = self.sampleNumber
data = numpy.zeros((n,self.numberOfChannel), dtype=numpy.float64)
read = int32()
self.ReadAnalogF64(n,10.0,PyDAQmx.DAQmx_Val_GroupByScanNumber,data,n*self.numberOfChannel,byref(read),None)
return data
def stop(self):
self.StopTask()
def wait(self, timeout=10):
self.WaitUntilTaskDone(timeout)


if __name__=="__main__":
ai = AIVoltageChan(ai_param=AIParameters(100000, 10000, ['/dev1/ai0', '/dev1/ai1']),
terminalConfig="DAQmx_Val_PseudoDiff",
trigger=RisingTrigger('/dev1/PFI0'))
ai.start()
ai.wait()
ai.read()
ai.stop()
Loading

0 comments on commit b6d7791

Please sign in to comment.