# PyEPL: hardware/eeg/scalp/scalp.pyx
#
# Copyright (C) 2003-2005 Michael J. Kahana
# Authors: Ian Schleifer, Per Sederberg, Aaron Geller, Josh Jacobs
# URL: http://memory.psych.upenn.edu/programming/pyepl
#
# Distributed under the terms of the GNU Lesser General Public License
# (LGPL). See the license.txt that came with this file.

"""
Module to communicate with a scalp EEG shared memory.
"""

from pyepl.exceptions import EPLException

class EPLScalpEEGException(EPLException):
    def __init__(self, desc):
        self.desc = desc
    def __str__(self):
        return "EPL EEG Exception: %s" % self.desc

# external declarations
cdef extern int eegAttached()
cdef extern int eegShmAttach()
cdef extern int eegShmDetach()
cdef extern int eegRecStart(char *filename)
cdef extern int eegRecStop()
cdef extern long eegGetOffset()

# error defines
ERROR_MBUFF_ATTACH = -1
ERROR_SHMEM_ATTACH = -2
ERROR_SHMEM_ACCESS = -3
ERROR_SHMEM_MAGIC = -4

# python wrappers
def shmAttached():
    """
    Check to see if the object is attached to shared memory.
    """
    return eegAttached()

def shmAttach():
    """
    Attach to the shared memory for communcation.
    """
    ret = eegShmAttach()
    if ret != 0:
        # error, so raise exception
        if ret == ERROR_MBUFF_ATTACH:
            raise EPLScalpEEGException("Unable to attach to kernel shared memory. Load rt_broker_module.o")
        elif ret == ERROR_SHMEM_ATTACH:
            raise EPLScalpEEGException("SHMGET: Did not attach to EEG shared memory.")
        elif ret == ERROR_SHMEM_ACCESS:
            raise EPLScalpEEGException("SHMAT: Could not access EEG shared memory.")
        elif ret == ERRO_SHMEM_MAGIC:
            raise EPLScalpEEGException("Shared memory does not have the right magic key. Check that the header versions are all in sync.")
        

def shmDetach():
    """
    Detach from shared memory.
    """
    ret = eegShmDetach()
    if ret != 0:
        raise EPLScalpEEGException("Did not detach from shared memory")
        
def recStart(char *filename):
    """
    Start recording to a file.

    You must specify the FULL PATH to the file!
    """
    ret = eegRecStart(filename)
    if ret != 0:
        raise EPLScalpEEGException("Could not start recording.")
    
def recStop():
    """
    Stop recording of a file is currently recording.
    """
    ret = eegRecStop()
    if ret != 0:
        raise EPLScalpEEGException("Could not stop recording.")
    
def getOffset():
    """
    Returns the offset into the file since starting recording.
    """
    return eegGetOffset()

