# General purpose Data AQuisition module
### Manuel M
### May 2010

import ctypes
import time

import UniversalLibrary as UL
import matplotlib.pyplot as plt
import numpy

class daq():
    """
    daq() is a general purpose Data Aquisition class, destined to be used as
    a parent class from which all of the other class will inherit
    """
    def __init__(self):
        pass


class mccdaq(daq):
    """
    mccdaq() is a class encapsulating the data acquisition functions of a
    measurement computing USB-1208FS card
    """
    def __init__(self):
        """
        constructor
        """
        self.boardId = 0
        self.sampleRate = 100
        self.chanCount = 1
        self.lowChan = 3
        self.highChan = 3
        self.bufferSize = 124*31
        self.buffer = numpy.zeros((self.bufferSize*self.chanCount,), numpy.int16)
        self.gain = UL.BIP5VOLTS
        self.curPos = 0

    def startSampling(self):
        print "DEBUG: attempting to start sampling on board %d"%self.boardId
        if self.isRunning():
            print "DEBUG: Board %d is already sampling"%self.boardId
            self.stopSampling()
        self.options = UL.CONVERTDATA + UL.BACKGROUND + UL.BLOCKIO + UL.CONTINUOUS
        try:
            self.sampleRate = UL.cbAInScan(self.boardId, self.lowChan, self.highChan, self.bufferSize*self.chanCount,
              self.sampleRate, self.gain, self.buffer,
              self.options)
        except Exception as e:
            print "DEBUG: Exception raised in mccdaq.startSampling()"
            print e

    def stopSampling(self):
        print "DEBUG: attempting to stop sampling on board %d"%self.boardId
        UL.cbStopIOBackground(self.boardId, UL.AIFUNCTION)

    def isRunning(self):
        status = 0
        curCount = 0
        curIndex= 0
        status, curCount, curIndex = UL.cbGetIOStatus(self.boardId, status, curCount, curIndex, UL.AIFUNCTION)
        if status == UL.RUNNING:
            print "IO is RUNNING. count: %d, index:%d"%(curCount,curIndex)
            return True
        else:
            print "IO is STOPPED"
            return False

    def onDataAvailable(self, inBoardNum, inEventType, inEventData, inUserData):
        userData = ctypes.cast(inUserData,ctypes.POINTER(ctypes.py_object)).contents.value
        print "in callBackTest()"
        print "BoardNum:%d, EventType:%d, EventData:%d, userdata:%s"%(inBoardNum, inEventType, inEventData, userData)
        if inEventData>self.curPos:
            newData = test.buffer[self.curPos:inEventData]
            print "got %d new data point:%s"%(len(newData),newData)
            self.curPos = inEventData


if __name__ == "__main__":
    test = mccdaq()
    callBackFunc = UL.CLBKFUNCTYPE(test.onDataAvailable)
    UL.cbEnableEvent(test.boardId, UL.ON_DATA_AVAILABLE, 1, callBackFunc, test)
    test.startSampling()
    time.sleep(100)
    test.stopSampling()
    

    