def _test_set_data_and_playback_states(self):
     bb = Blackboard()
     sim = DataSimulator( bb )
     
     reader = HDFReader();
      
     filename = filenames[5][0]
      
     # Reading two datafiles
     [ mat, frequencies, _ ] = reader.read(filename)       # Read data from first data file
     data = [ np.asarray( mat[i-1][ 1 ] ) for i in range(1,9) ]       # get data from selected channels
     patterns = ['/EEG/channel_%d' % (i) for i in range(1,9) ]
     
     interval = 1. / frequencies[ 1 ]  
     
     sim.set_simulation_data(data)
     sim.set_simulation_interval(interval)
     sim.set_patterns(patterns)
     
     self.assertEqual(sim.get_simulation_state(), DataSimulator.IDLE, "Simulator should be idle now")
     sim.start()
     time.sleep(.1)
     self.assertEqual(sim.get_simulation_state(), DataSimulator.PLAYING, "Simulator should be playing now")
     sim.pause()
     time.sleep(.1)
     self.assertEqual(sim.get_simulation_state(), DataSimulator.PAUSED, "Simulator should be paused now")
     sim.start()
     time.sleep(.1)
     self.assertEqual(sim.get_simulation_state(), DataSimulator.PLAYING, "Simulator should be playing now")
     sim.stop()
     time.sleep(.1)
     self.assertEqual(sim.get_simulation_state(), DataSimulator.IDLE, "Simulator should be stopped now")
 
     self.assertTrue(bb.get_count(patterns[0]) > 0, "Samples should be received on blackboard")
class TestFreqSpectrum(unittest.TestCase):

    def setUp(self):
        unittest.TestCase.setUp(self)
        self.bb = Blackboard()
        pattern = '/sines'
        
        self.offset         = 10
        self.frequencies    = [1,3,5,7]
        self.amps           = [1,2,1,8]
        
        self.gen            = DataGenerator( self.bb, pattern, frequencies=self.frequencies, amplitudes=self.amps, offset=self.offset, noise=0 )
        self.freqspec       = FFTAnalyzer( self.bb, pattern, windowsize=256 )
        self.bb.set_bufsize( '/sines/fft', 128 )

    def test_fft(self):
        self.gen.start()
        self.freqspec.start()
        
        sleep( 3 )
        
        self.gen.stop()
        self.freqspec.stop()

        result = self.bb.get_data('/sines/fft')
        
        # Enable when code coverage is guaranteed
        #self.assertAlmostEqual( result['data'], self.offset, msg="Offset difference too big", delta=.15 )
        
        #for f,amp in zip(self.frequencies,self.amps):
        #    self.assertAlmostEqual( result[f], amp, msg="Power difference too big: freq %f - original %f - measured %f" % (f, amp, result[f]), delta=.15 )
        
    def test_setFreqBands(self):
        '''
            Verify if frequency bands can be set
            For now only call the function for code coverage
        '''
        test_freq = 10

        self.freqspec.setFreqBands(test_freq)


    def test_setPatterns(self):
        '''
            Verify if patterns can be set
            For now only call the function for code coverage
        '''
        test_pattern = '/test'

        self.freqspec.setPatterns(test_pattern)

    def test_resetBuffers(self):
        '''
            Verify if buffers can be reset
            For now only call the function for code coverage
        '''
        self.freqspec.resetBuffers()

    def tearDown(self):
        unittest.TestCase.tearDown(self)
Esempio n. 3
0
    def setUp(self):
        unittest.TestCase.setUp(self)
        self.blackboard = Blackboard()

        self.pat = '/test'
        self.gen = DataGenerator(self.blackboard, self.pat, [1], [1])
        self.gen.start()
        self.pat2 = '/test2'
        self.gen2 = DataGenerator(self.blackboard, self.pat2, [2], [1])
        self.gen2.start()
Esempio n. 4
0
class TestBasePlot(unittest.TestCase):
    def setUp(self):
        self.bb = Blackboard()
        self.pattern = "/foo"
        self._fig, self._ax = plt.subplots(1)

    def test_init_no_blackboard(self):

        with self.assertRaises(ValueError):
            BasePlot("foo", [self.pattern], self._ax)

    def test_update_ax(self):
        baseplot = BasePlot(self.bb, [self.pattern], self._ax)

        with self.assertRaises(NotImplementedError):
            baseplot._update_ax()

    def test_process_plot_data(self):
        baseplot = BasePlot(self.bb, [self.pattern], self._ax)

        with self.assertRaises(NotImplementedError):
            baseplot._process_plot_data(None, None, None)

    def test_process_data(self):

        offset = 5000
        frequencies = [1, 3, 5, 7]
        amps = [1, 2, 1, 8]

        baseplot = BasePlot(self.bb, [self.pattern], self._ax)
        baseplot._process_plot_data = fake_function

        gen = DataGenerator(self.bb,
                            self.pattern,
                            frequencies=frequencies,
                            amplitudes=amps,
                            offset=offset,
                            noise=0)

        self.bb.set_bufsize(self.pattern, 128)

        gen.start()

        baseplot.start()

        sleep(10)

        baseplot.stop()
        gen.stop

    def tearDown(self):
        unittest.TestCase.tearDown(self)
class TestBasePlot(unittest.TestCase):

    def setUp(self):        
        self.bb = Blackboard()
        self.pattern = "/foo"
        self._fig, self._ax = plt.subplots( 1 )
        
    def test_init_no_blackboard(self):

        with self.assertRaises(ValueError):
            BasePlot("foo", [self.pattern], self._ax)

    def test_update_ax(self):
        baseplot = BasePlot(self.bb, [self.pattern], self._ax)

        with self.assertRaises(NotImplementedError):
            baseplot._update_ax()

    def test_process_plot_data(self):
        baseplot = BasePlot(self.bb, [self.pattern], self._ax)

        with self.assertRaises(NotImplementedError):
            baseplot._process_plot_data(None, None, None)

    def test_process_data(self):

        offset         = 5000
        frequencies    = [1,3,5,7]
        amps           = [1,2,1,8]

        baseplot = BasePlot(self.bb, [self.pattern], self._ax)
        baseplot._process_plot_data = fake_function

        gen      = DataGenerator( self.bb, self.pattern, frequencies=frequencies, amplitudes=amps, offset=offset, noise=0 )

        self.bb.set_bufsize( self.pattern, 128 )

        gen.start() 

        baseplot.start()

        sleep(10)

        baseplot.stop()
        gen.stop

    def tearDown(self):
        unittest.TestCase.tearDown(self)
Esempio n. 6
0
    def test_reset(self):
        '''
            Call the reset function to improve (functional) code coverage
        '''
        blackboard = Blackboard()
        simulator = DataSimulator(blackboard)

        simulator.reset()
Esempio n. 7
0
    def test_get_current_time(self):
        '''
            Call the get_current_time function to improve (functional) code coverage
        '''
        blackboard = Blackboard()
        simulator = DataSimulator(blackboard)

        self.assertEqual(simulator.get_current_time(), -1)
Esempio n. 8
0
    def test_set_time(self):
        '''
            Call the set_time function to improve (functional) code coverage
        '''
        blackboard = Blackboard()
        simulator = DataSimulator(blackboard)

        simulator.set_time(5)
Esempio n. 9
0
    def setUp(self):
        unittest.TestCase.setUp(self)
        self.bb = Blackboard()
        pattern = '/sines'

        self.offset = 10
        self.frequencies = [1, 3, 5, 7]
        self.amps = [1, 2, 1, 8]

        self.gen = DataGenerator(self.bb,
                                 pattern,
                                 frequencies=self.frequencies,
                                 amplitudes=self.amps,
                                 offset=self.offset,
                                 noise=0)
        self.freqspec = FFTAnalyzer(self.bb, pattern, windowsize=256)
        self.bb.set_bufsize('/sines/fft', 128)
Esempio n. 10
0
    def setUp(self):
        """
        Initialize blackboard and a simulation data generator
        """
        unittest.TestCase.setUp(self)
        self.bb = Blackboard()
        self.pattern = '/sines'

        self.offset = 10
        self.frequencies = [50, 10]
        self.amps = [1, 1]

        self.gen = DataGenerator(self.bb,
                                 self.pattern,
                                 frequencies=self.frequencies,
                                 amplitudes=self.amps,
                                 offset=self.offset,
                                 noise=0)
Esempio n. 11
0
    def _test_set_data_and_playback_states(self):
        bb = Blackboard()
        sim = DataSimulator(bb)

        reader = HDFReader()

        filename = filenames[5][0]

        # Reading two datafiles
        [mat, frequencies,
         _] = reader.read(filename)  # Read data from first data file
        data = [np.asarray(mat[i - 1][1])
                for i in range(1, 9)]  # get data from selected channels
        patterns = ['/EEG/channel_%d' % (i) for i in range(1, 9)]

        interval = 1. / frequencies[1]

        sim.set_simulation_data(data)
        sim.set_simulation_interval(interval)
        sim.set_patterns(patterns)

        self.assertEqual(sim.get_simulation_state(), DataSimulator.IDLE,
                         "Simulator should be idle now")
        sim.start()
        time.sleep(.1)
        self.assertEqual(sim.get_simulation_state(), DataSimulator.PLAYING,
                         "Simulator should be playing now")
        sim.pause()
        time.sleep(.1)
        self.assertEqual(sim.get_simulation_state(), DataSimulator.PAUSED,
                         "Simulator should be paused now")
        sim.start()
        time.sleep(.1)
        self.assertEqual(sim.get_simulation_state(), DataSimulator.PLAYING,
                         "Simulator should be playing now")
        sim.stop()
        time.sleep(.1)
        self.assertEqual(sim.get_simulation_state(), DataSimulator.IDLE,
                         "Simulator should be stopped now")

        self.assertTrue(
            bb.get_count(patterns[0]) > 0,
            "Samples should be received on blackboard")
 def setUp(self):
     unittest.TestCase.setUp(self)
     self.blackboard = Blackboard()
     
     self.pat = '/test'
     self.gen = DataGenerator( self.blackboard, self.pat, [1], [1] )
     self.gen.start()
     self.pat2 = '/test2'
     self.gen2 = DataGenerator( self.blackboard, self.pat2, [2], [1] )
     self.gen2.start()
Esempio n. 13
0
    def test_set_simulation_data(self):
        ''' 
            Verify if the simulation data can be set 
            Only function is called to improve (functional) code coverage, so no verification yet
        '''
        blackboard = Blackboard()
        simulator = DataSimulator(blackboard)
        sim_data = self.create_simulation_data()

        simulator.set_simulation_data(sim_data)
Esempio n. 14
0
    def test_pause(self):
        '''
            Call the pause function to improve (functional) code coverage
        '''
        blackboard = Blackboard()
        simulator = DataSimulator(blackboard)

        simulator.set_state(self.states.get('PLAYING'))
        simulator.pause()
        self.assertEqual(simulator.get_simulation_state(),
                         self.states.get('PAUSED'))
Esempio n. 15
0
    def test_get_set_simulation_state(self):
        ''' 
            Verify if the getting and setting of simulation states works correctly
        '''
        blackboard = Blackboard()
        simulator = DataSimulator(blackboard)

        # Set all the states and verify if the state is set correctly
        for _, value in self.states.iteritems():
            simulator.set_state(value)
            self.assertEqual(simulator.get_simulation_state(), value)
class TestDataConsumer(unittest.TestCase):

    def setUp(self):
        unittest.TestCase.setUp(self)
        self.blackboard = Blackboard()
        
        self.pat = '/test'
        self.gen = DataGenerator( self.blackboard, self.pat, [1], [1] )
        self.gen.start()
        self.pat2 = '/test2'
        self.gen2 = DataGenerator( self.blackboard, self.pat2, [2], [1] )
        self.gen2.start()

    def test_singel_data_stream(self):
        """
        Test whether data of single is coming through
        """
        DataConsumer( self.blackboard, self.pat )
        sleep( .5 )
        
        result = self.blackboard.get_data( self.pat )
        self.assertIsNotNone( result )
        self.assertGreater(len(result), 0 )

    def test_multiple_data_streams(self):
        DataConsumer( self.blackboard, [self.pat, self.pat2] )
        sleep( .5 )
        
        result = self.blackboard.get_data( self.pat )
        self.assertIsNotNone( result )
        self.assertGreater(len(result), 0 )
        
        result = self.blackboard.get_data( self.pat2 )
        self.assertIsNotNone( result )
        self.assertGreater(len(result), 0 )

        
    def tearDown(self):
        unittest.TestCase.tearDown(self)
        self.gen.stop()
        self.gen2.stop()
 def setUp(self):
     unittest.TestCase.setUp(self)
     self.bb = Blackboard()
     pattern = '/sines'
     
     self.offset         = 10
     self.frequencies    = [1,3,5,7]
     self.amps           = [1,2,1,8]
     
     self.gen            = DataGenerator( self.bb, pattern, frequencies=self.frequencies, amplitudes=self.amps, offset=self.offset, noise=0 )
     self.freqspec       = FFTAnalyzer( self.bb, pattern, windowsize=256 )
     self.bb.set_bufsize( '/sines/fft', 128 )
 def setUp(self):
     """
     Initialize blackboard and a simulation data generator
     """
     unittest.TestCase.setUp( self )
     self.bb      = Blackboard()
     self.pattern = '/sines'
     
     self.offset         = 10
     self.frequencies    = [50,10]
     self.amps           = [1,1]
     
     self.gen            = DataGenerator( self.bb, self.pattern, frequencies=self.frequencies, amplitudes=self.amps, offset=self.offset, noise=0 )
Esempio n. 19
0
class TestDataConsumer(unittest.TestCase):
    def setUp(self):
        unittest.TestCase.setUp(self)
        self.blackboard = Blackboard()

        self.pat = '/test'
        self.gen = DataGenerator(self.blackboard, self.pat, [1], [1])
        self.gen.start()
        self.pat2 = '/test2'
        self.gen2 = DataGenerator(self.blackboard, self.pat2, [2], [1])
        self.gen2.start()

    def test_singel_data_stream(self):
        """
        Test whether data of single is coming through
        """
        DataConsumer(self.blackboard, self.pat)
        sleep(.5)

        result = self.blackboard.get_data(self.pat)
        self.assertIsNotNone(result)
        self.assertGreater(len(result), 0)

    def test_multiple_data_streams(self):
        DataConsumer(self.blackboard, [self.pat, self.pat2])
        sleep(.5)

        result = self.blackboard.get_data(self.pat)
        self.assertIsNotNone(result)
        self.assertGreater(len(result), 0)

        result = self.blackboard.get_data(self.pat2)
        self.assertIsNotNone(result)
        self.assertGreater(len(result), 0)

    def tearDown(self):
        unittest.TestCase.tearDown(self)
        self.gen.stop()
        self.gen2.stop()
Esempio n. 20
0
    def setUp(self):
        self.nr_of_headsets = 2
        self.channels = [1, 2, 3, 4]
        self.processors = []

        self.bb = Blackboard()

        patterns = []
        for channel in [1, 3]:
            for freq in [PatternStrings.ALPHA, PatternStrings.BETA]:
                patterns.append(PatternStrings.SIGNAL_EEG + '%d' % (1) +
                                PatternStrings.CHANNEL + '%d' % (channel) +
                                freq)

        self.processor = ArousalProcessor(self.bb, patterns)
Esempio n. 21
0
    def test_play_stop(self):
        blackboard = Blackboard()
        simulator = DataSimulator(blackboard)

        # Prepare the simulator preconditions
        simulator.set_simulation_data("test")
        simulator.set_patterns("test")
        simulator.set_simulation_interval(1)

        simulator.start()
        simulator.stop()

        simulator.set_state(self.states.get('PAUSED'))
        simulator.start()
        simulator.stop()
Esempio n. 22
0
    def _test_get_time(self):
        bb = Blackboard()
        sim = DataSimulator(bb)

        reader = HDFReader()

        filename = filenames[5][0]

        # Reading two datafiles
        [mat, frequencies,
         _] = reader.read(filename)  # Read data from first data file
        data = [np.asarray(mat[i - 1][1])
                for i in range(1, 9)]  # get data from selected channels
        patterns = ['/EEG/channel_%d' % (i) for i in range(1, 9)]

        interval = 1. / frequencies[1]

        sim.set_simulation_data(data)
        sim.set_simulation_interval(interval)
        sim.set_patterns(patterns)

        total_time = sim.get_total_time()

        start_time = sim.get_current_time()
        self.assertEquals(start_time, 0, 'Time should be zero before playback')

        sim.start()

        time.sleep(3)

        now_time = sim.get_current_time()
        self.assertAlmostEquals(
            now_time,
            3,
            msg='Time should be close to 3 after 3 seconds playback. Is %f' %
            now_time,
            delta=.05)

        sim.set_time(total_time - 2)
        self.assertTrue(sim.get_simulation_state() is DataSimulator.PLAYING,
                        'Should be playing after setting time')

        time.sleep(3)

        self.assertTrue(sim.get_simulation_state() is DataSimulator.IDLE,
                        'Should be done playing')

        sim.stop()
Esempio n. 23
0
    def setUp(self):
        unittest.TestCase.setUp(self)
        self.bb = Blackboard()
        self.sim = TimedSimulator(self.bb)

        [mat,
         _] = HDFReader().read(test_filename)  # Read data from first data file
        _data = []
        for i in range(4):
            _data.append([v[:2] for v in mat[i][1]])
        self.sim.set_simulation_data(_data)

        eeg_chans = [
            '/EEG_0/channel_%d/notch_50/lpf_75' % (i + 1) for i in range(4)
        ]

        self.sim.set_patterns(eeg_chans)
Esempio n. 24
0
 def setUp(self):
     self.bb = Blackboard()
     self.pattern = "/foo"
     self._fig, self._ax = plt.subplots(1)
Esempio n. 25
0
 def setUp(self):
     self.bb = Blackboard()
     self.input = HDFReader()
Esempio n. 26
0
class TestFirPreprocessing(unittest.TestCase):
    def setUp(self):
        self.bb = Blackboard()
        self.input = HDFReader()

    def create_filters(self):
        # create preprocessing filters
        self._processors = []

        self.headset = 0
        self.channel = 1

        notch = 50
        lowpass = 80

        filter_pattern1 = '/lpf%d' % (lowpass)
        filter_pattern2 = '/notch%d' % (notch)

        self.pat = '/eeg%d/channel_%d' % (self.headset, self.channel)
        lp = IIRLowPassFilter(self.bb, [self.pat], lowpass=lowpass)
        self._processors.append(lp)
        self.pat_lpf = self.pat + filter_pattern1

        nf = IIRNotchFilter(self.bb, [self.pat_lpf],
                            cutoff_freq=notch,
                            cutoff_width=1)
        self._processors.append(nf)
        self.pat_notch = self.pat_lpf + filter_pattern2

        nf = IIRNotchFilter(self.bb, [self.pat],
                            cutoff_freq=notch,
                            cutoff_width=1)
        self._processors.append(nf)
        self.pat_notch1 = self.pat + filter_pattern2

        pp = FIRPreprocessing(self.bb, [self.pat])
        self._processors.append(pp)
        self.pat_pp = self.pat + '/pp'

    def test_start(self):
        self.create_filters()

        offset = 5000
        plot_size = 1000
        offset = 5000
        last_count = 0
        result = []
        frequencies = [1, 3, 5, 7]
        amps = [1, 2, 1, 8]

        gen = DataGenerator(self.bb,
                            self.pat,
                            frequencies=frequencies,
                            amplitudes=amps,
                            offset=offset,
                            noise=0)

        self.bb.set_bufsize(self.pat_pp, 128)

        gen.start()

        # Start filters
        for p in self._processors:
            p.start()

        sleep(1)

        # Start processing data
        #for d in self.original[:]:
        #    self.bb.put_data( self.pat, d )
        #    local_count = self.bb.get_count( self.pat )
        #    dif = local_count - last_count
        #    if dif > 0:
        #        last_count = local_count
        #        local_results = self.bb.get_data( self.pat_pp )['data']
        #        if local_results:
        #            local_results = local_results[-dif:]
        #            for r in local_results:
        #                result.append(r)
        #    sleep(.00001)

        sleep(3)

        # Stop filters
        for p in self._processors:
            p.stop()

        gen.stop()

    def test_init_firpreprocessing_pattern_no_string(self):

        with self.assertRaises(TypeError):
            FIRPreprocessing(self.bb, 2)

    def tearDown(self):
        unittest.TestCase.tearDown(self)
Esempio n. 27
0
class TestFreqSpectrum(unittest.TestCase):
    def setUp(self):
        unittest.TestCase.setUp(self)
        self.bb = Blackboard()
        pattern = '/sines'

        self.offset = 10
        self.frequencies = [1, 3, 5, 7]
        self.amps = [1, 2, 1, 8]

        self.gen = DataGenerator(self.bb,
                                 pattern,
                                 frequencies=self.frequencies,
                                 amplitudes=self.amps,
                                 offset=self.offset,
                                 noise=0)
        self.freqspec = FFTAnalyzer(self.bb, pattern, windowsize=256)
        self.bb.set_bufsize('/sines/fft', 128)

    def test_fft(self):
        self.gen.start()
        self.freqspec.start()

        sleep(3)

        self.gen.stop()
        self.freqspec.stop()

        result = self.bb.get_data('/sines/fft')

        # Enable when code coverage is guaranteed
        #self.assertAlmostEqual( result['data'], self.offset, msg="Offset difference too big", delta=.15 )

        #for f,amp in zip(self.frequencies,self.amps):
        #    self.assertAlmostEqual( result[f], amp, msg="Power difference too big: freq %f - original %f - measured %f" % (f, amp, result[f]), delta=.15 )

    def test_setFreqBands(self):
        '''
            Verify if frequency bands can be set
            For now only call the function for code coverage
        '''
        test_freq = 10

        self.freqspec.setFreqBands(test_freq)

    def test_setPatterns(self):
        '''
            Verify if patterns can be set
            For now only call the function for code coverage
        '''
        test_pattern = '/test'

        self.freqspec.setPatterns(test_pattern)

    def test_resetBuffers(self):
        '''
            Verify if buffers can be reset
            For now only call the function for code coverage
        '''
        self.freqspec.resetBuffers()

    def tearDown(self):
        unittest.TestCase.tearDown(self)
Esempio n. 28
0
    def __init__(self):
        Subject.__init__( self )
        self.nr_of_headsets = 2
        self.channels       = [1,2,3,4]
        
        self.blackboard     = Blackboard()
        self.simulators     = []
        self.headsets       = []
        self.processors     = []
        self.filerecorders  = []
        self.oscwriters     = []
        
        self._connected_headsets = 0

        self.timeSettings = TimeSettings()
        self.frequencySpectrumSettings =SpectrumSettings()
        self.frequencyBandSettings = FrequencyBandSettings()
        
        # Initialize simulators
        for _ in range( self.nr_of_headsets ):
            self.simulators.append( TimedSimulator( self.blackboard ) ) 
        
        # Initialize headsets
        for headset in range( self.nr_of_headsets ):
            self.headsets.append( ImecInput( self.blackboard, PatternStrings.SIGNAL_EEG + '%d' % (headset) ) )
        
        # Initialize preprocessing filters
        for i, channel in enumerate(self.channels):
            for headset in range( self.nr_of_headsets ):
                pat = PatternStrings.SIGNAL_EEG + '%d' % (headset) + PatternStrings.CHANNEL + '%d' % (channel)
                
                # Add notch filtering
                notch = FIRFilter( self.blackboard, pat, FilterSettings.NOTCH_NUMTAPS, FilterSettings.NOTCH_FS, FilterSettings.NOTCH_FREQ, 'notch' )
                notch.start(name = 'fir_notch' + pat)
                self.processors.append( notch )
                
                pat += PatternStrings.FILTERNOTCH
                
                # Add low-pass filtering
                lpf = FIRFilter( self.blackboard, pat, FilterSettings.LPF_NUMTAPS, FilterSettings.LPF_FS, FilterSettings.LPF_FREQ, 'lpf' )
                lpf.start(name = 'fir_lpf' + pat)
                self.processors.append( lpf )
                
        # Patterns that will be recorded
        patterns = []
        for headset in range(self.nr_of_headsets):
            patterns.append( [(PatternStrings.SIGNAL_EEG + '%d' % (headset) + PatternStrings.CHANNEL + '%d' % (i))
                               for i in self.channels])
            
        names = [SignalNames.RAWSIGNAL for _ in self.channels ]
        
        # Initialize recorders
        for i, pat in enumerate(patterns):
            rec = FileRecorder( self.blackboard, pat, self.channels, names, writer=IMECWriter() )
            rec.start( interval=10, name = 'recorder-%d' % i )
            self.filerecorders.append( rec )
        
        # Perform FFT only on raw signals
        patterns = []
        for headset in range(self.nr_of_headsets):
            patterns.append( [(PatternStrings.SIGNAL_EEG + '%d' % (headset) + PatternStrings.CHANNEL + '%d' % (i)) for i in self.channels] )
        
        # Initialize FFT analyzer
        freqspec = FFTAnalyzer(self.blackboard, sum(patterns, [])) # NOTE: Could be made faster by using for's i.s.o. sum, but for init-code not really relevant
        #freqspec.start() DO NOT START FFT AT INIT
        self.processors.append( freqspec )
        
        # Initialize Arousal processors
        for headset in range(self.nr_of_headsets):
            patterns = []
            for channel in [1,3]:
                for freq in [PatternStrings.ALPHA, PatternStrings.BETA]:
                    patterns.append(PatternStrings.SIGNAL_EEG + '%d' % (headset) + PatternStrings.CHANNEL + '%d' % (channel) + freq)
            
            # Initialize Arousal processor
            arousal = ArousalProcessor(self.blackboard, patterns)
            #arousal.start() DO NOT START ArousalProcessor AT INIT
            self.processors.append( arousal )
 def setUp(self):        
     self.bb         = Blackboard()
     self.input      = HDFReader()
class TestImecInput(unittest.TestCase):

    def startUp(self):
        '''
        Helper-method for starting up headset-simulator, opening COM-port and set connection
        '''
        # Start headset-simulator
        self.hs_simulator = SerialSimulator()
        self.hs_simulator.start()

        # Get socket for serial connection
        self._socket = SerialSocket(Testing.SERIAL_PORT)

        # And pass this socket to imec
        self.imec.set_connection(self._socket)
    
    def setUp(self):
        self.test_pattern = 'test_eeg'
        self.test_buffer  = Blackboard()
        self.imec         = ImecInput(self.test_buffer, self.test_pattern)

    def tearDown(self):
        self.test_buffer.clear(self.test_pattern)

#     @unittest.skip('skip test_01')
    def test_01_init(self):
        """
        Test initalization of ImecInput
        """
        self.assertEqual(self.imec.blackboard, self.test_buffer, "Blackboard not set")
        self.assertEqual(self.imec._pattern, self.test_pattern, "Incorrect pattern")
        self.assertTrue(self.imec._socket == None, "Socket should not be set")

        self.assertFalse(self.imec.start('hs1'), "Start streaming should fail")
        self.assertFalse(self.imec.is_streaming(), "Should not be streaming")
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

    @patch('serial.Serial')
    def test_02_startStreaming(self, serial_mock):
        """
        Test start/stop streaming with/without connection 
        """
        self.startUp()

        serial_mock.return_value = SerialMock

        self.assertTrue(self.imec.is_connected(), "Should be connected")
        self.assertFalse(self.imec.is_streaming(), "Should not be streaming yet")

        # Start streaming
        self.assertTrue(self.imec.start('hs1'), "Start streaming failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(0.2)

        self.assertFalse(self.imec.start('hs2'), "Start during streaming should fail")

        self.imec.stop()
        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.hs_simulator.stop()

        self.assertFalse(self.imec.is_streaming(), "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        self.imec.disconnect()
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

    @patch('serial.Serial')
    def test_03_restartAfterStop(self, serial_mock):
        self.startUp()

        serial_mock.return_value = SerialMock

        self.assertTrue(self.imec.is_connected(), "Should be connected")

        self.assertTrue(self.imec.start('hs1'), "Start streaming failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(.2)

        # Stop streaming
        self.imec.stop()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.assertFalse(self.imec.is_streaming(), "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        # Restart streaming
        self.assertTrue(self.imec.start('hs2'), "Restart streaming failed")
        self.assertTrue(self.imec.is_streaming(), "Not streaming after restart")

        sleep(.2)

        self.imec.stop()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.hs_simulator.stop()

        self.assertFalse(self.imec.is_streaming(), "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        self.imec.disconnect()
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

    @patch('serial.Serial')
    def test_04_disconnectDuringStreaming(self, serial_mock):
        self.startUp()

        serial_mock.return_value = SerialMock

        self.assertTrue(self.imec.is_connected(), "Should be connected")

        self.assertTrue(self.imec.start('hs1'), "Start streaming failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(.2)

        # Disconnect during streaming -> streaming should stop
        self.imec.disconnect()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.assertFalse(self.imec.is_connected(), "Should be disconnected")
        self.assertFalse(self.imec.is_streaming(), "Still streaming after disconnect during streaming")
        self.assertFalse(self.imec.start('hs2'), "Start streaming should fail after disconnect")

        # Reconnect
        self.imec.set_connection(self._socket)
        self.assertTrue(self.imec.is_connected(), "Should be connected")
        self.assertFalse(self.imec.is_streaming(), "Should not be streaming yet")

        self.assertTrue(self.imec.start('hs3'), "Start streaming after reconnect failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(.2)

        self.imec.stop()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.hs_simulator.stop()

        self.assertFalse(self.imec.is_streaming(), "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        self.imec.disconnect()
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

    @patch('serial.Serial')
    def test_05_parseEEG(self, serial_mock):
        """
        Test parsing EEG-data
        """
        self.startUp()

        serial_mock.return_value = SerialMock

        self.assertTrue(self.imec.is_connected(), "Should be connected")
        self.assertFalse(self.imec.is_streaming(), "Should not be streaming yet")

        # Start streaming
        self.assertTrue(self.imec.start('hs1'), "Start streaming failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(.2)

        self.imec.stop()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.hs_simulator.stop()

        self.assertFalse(self.imec.is_streaming(), "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        self.imec.disconnect()
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

        #for ch in range(4):
        #    count = self.test_buffer.get_count(self.test_pattern + '/channel_%d' % (ch + 1))
        #    #self.assertGreater(count, 0)

        #    data = self.test_buffer.get_data(self.test_pattern + '/channel_%d' % (ch + 1), count)
        #    self.assertEqual(len(data['data']), count, "Sample-count doesn't match")
        #    self.assertEqual(len(data['timestamps']), count, "Timestamp-count doesn't match")

        #    #print 'Received %d samples on channel %d' % (count, (ch + 1))
            
        #    for sample, timestamp in zip(data[0], data[1]):
        #        self.assertEqual(timestamp % 0.00390625, 0.0, "Timestamp failure")
        #        self.assertGreaterEqual(sample, 0, "Sample-value too low")
        #        self.assertLessEqual(sample, 4000, "Sample-value too high")

    def test_get_battery(self):
        self.assertEqual(self.imec.get_battery(), -1)

    def test_get_duration(self):
        self.assertEqual(self.imec.get_duration(), 0)

    def test_get_serial_state(self):
        self.assertEqual(self.imec.get_serial_state(), 0)

    def test_get_port_state(self):
        self.assertEqual(self.imec.get_port_state(), 0)

    def test_get_time(self):
        self.assertEqual(self.imec.get_time(), 0)
 def setUp(self):
     self.test_pattern = 'test_eeg'
     self.test_buffer  = Blackboard()
     self.imec         = ImecInput(self.test_buffer, self.test_pattern)
Esempio n. 32
0
class TestFIRFilter(unittest.TestCase):
    def setUp(self):
        """
        Initialize blackboard and a simulation data generator
        """
        unittest.TestCase.setUp(self)
        self.bb = Blackboard()
        self.pattern = '/sines'

        self.offset = 10
        self.frequencies = [50, 10]
        self.amps = [1, 1]

        self.gen = DataGenerator(self.bb,
                                 self.pattern,
                                 frequencies=self.frequencies,
                                 amplitudes=self.amps,
                                 offset=self.offset,
                                 noise=0)

    def test_init_notch(self):
        """
        Compare the generation of notch filter coefficients with the coefficients provided by Imec
        """
        notch_template = FIRPreprocessing.coefBSF256

        fir = FIRFilter(self.bb, self.pattern, 129, 256, 50, 'notch')
        self.assertEqual(len(notch_template), len(fir.get_coefficients()),
                         'sets should be equal length')
        self.assertAlmostEqual(
            sum([
                abs(x - y)
                for x, y in zip(notch_template, fir.get_coefficients())
            ]), 0, 5, 'difference should be small')

    def test_init_lpf(self):
        """
        Compare the generation of low-pass filter coefficients with the coefficients provided by Imec
        """
        lpf_template = FIRPreprocessing.coefLPF256

        fir = FIRFilter(self.bb, self.pattern, 33, 256, 75, 'lpf')
        coef = fir.get_coefficients()

        self.assertAlmostEqual(
            sum([abs(x - y) for x, y in zip(lpf_template, coef)]), 0, 2,
            'difference should be small')

    def test_elementwise_lfilter(self):
        """
        Test whether our method of elementwise processing yields the same results as processing a whole signal at once
        """
        fir = FIRFilter(self.bb, self.pattern, 33, 256, 75, 'lpf')
        a = 1
        sig = [randint(0, 1024) for _ in range(256)]

        result = lfilter(fir.get_coefficients(), a, sig, axis=0)

        result2 = []
        buf = []
        for s in sig:
            buf.append(s)
            buf = buf[-33:]
            result2.append(lfilter(fir.get_coefficients(), a, buf)[-1])

        self.assertEqual(len(result), len(result2),
                         'Results should be equal length')
        self.assertEqual(sum([abs(x - y) for x, y in zip(result, result2)]), 0,
                         'Results should be equal value')

    def test_notch50(self):
        """
        TODO Improve test with better timing mechanism or decouple from internal timing mechanism
        When plotting the results, the filtered signal looks really good though.
        """
        fir = FIRFilter(self.bb, self.pattern, 129, 256, 50, 'notch')

        self.gen2 = DataGenerator(self.bb,
                                  '/sine',
                                  frequencies=[10],
                                  amplitudes=[1],
                                  offset=self.offset,
                                  noise=0)

        self.bb.set_bufsize('/sine', 512)
        self.bb.set_bufsize('/sines/notch_50', 512)

        self.gen.start()
        self.gen2.start()
        fir.start()

        time.sleep(3)

        self.gen.stop()
        self.gen2.stop()
        fir.stop()

        time.sleep(1)

        off = len(fir.get_coefficients())

        target = self.bb.get_data('/sine')['data'][(off - 1) / 2:128 +
                                                   (off - 1) / 2]
        result = self.bb.get_data('/sines/notch_50')['data'][:128]

        #dif = np.average([ abs( x-y ) for x,y in zip(result, target ) ])
        #delta = 1
        #self.assertAlmostEqual( dif, 0, msg='Difference between target and result should be smaller than %.2f, difference is %f'%(delta,dif), delta=delta)

    def test_init_pattern_no_string(self):

        # An TypeError should be raised when a pattern is no string
        with self.assertRaises(TypeError):
            FIRFilter(self.bb, 5, 129, 256, 50, 'notch')

    def test_init_not_implemented_filter(self):

        # An NotImplementedError should be raised
        with self.assertRaises(NotImplementedError):
            FIRFilter(self.bb, self.pattern, 129, 256, 50, 'bsf')

    def test_init_incompatible_filter(self):

        # An TyperError should be raised
        with self.assertRaises(TypeError):
            FIRFilter(self.bb, self.pattern, 129, 256, 50, 'foo')

    def test_init_pattern_list(self):
        # For codecoverage
        FIRFilter(self.bb, [self.pattern], 129, 256, 50, 'notch')
Esempio n. 33
0
 def setUp(self):        
     self.bb = Blackboard()
     self.pattern = "/foo"
     self._fig, self._ax = plt.subplots( 1 )
Esempio n. 34
0
 def setUp(self):
     self.test_pattern = 'test_eeg'
     self.test_buffer = Blackboard()
     self.imec = ImecInput(self.test_buffer, self.test_pattern)
class TestFIRFilter( unittest.TestCase ):
    
    def setUp(self):
        """
        Initialize blackboard and a simulation data generator
        """
        unittest.TestCase.setUp( self )
        self.bb      = Blackboard()
        self.pattern = '/sines'
        
        self.offset         = 10
        self.frequencies    = [50,10]
        self.amps           = [1,1]
        
        self.gen            = DataGenerator( self.bb, self.pattern, frequencies=self.frequencies, amplitudes=self.amps, offset=self.offset, noise=0 )
    
    def test_init_notch(self):
        """
        Compare the generation of notch filter coefficients with the coefficients provided by Imec
        """
        notch_template = FIRPreprocessing.coefBSF256

        fir = FIRFilter( self.bb, self.pattern, 129, 256, 50, 'notch' )
        self.assertEqual( len(notch_template), len(fir.get_coefficients() ), 'sets should be equal length')
        self.assertAlmostEqual( sum([ abs( x-y ) for x,y in zip(notch_template, fir.get_coefficients() ) ]), 0, 5, 'difference should be small')
        
    def test_init_lpf(self):
        """
        Compare the generation of low-pass filter coefficients with the coefficients provided by Imec
        """
        lpf_template = FIRPreprocessing.coefLPF256

        fir  = FIRFilter( self.bb, self.pattern, 33, 256, 75, 'lpf' )
        coef = fir.get_coefficients()
           
        self.assertAlmostEqual( sum([ abs( x-y ) for x,y in zip(lpf_template, coef ) ]), 0, 2, 'difference should be small')
        
    def test_elementwise_lfilter(self):
        """
        Test whether our method of elementwise processing yields the same results as processing a whole signal at once
        """
        fir = FIRFilter( self.bb, self.pattern, 33, 256, 75, 'lpf' )
        a   = 1
        sig = [ randint(0,1024) for _ in range(256) ]
        
        result = lfilter( fir.get_coefficients(), a, sig, axis=0 ) 

        result2 = []
        buf = []
        for s in sig:
            buf.append(s)
            buf = buf[-33:]
            result2.append(lfilter( fir.get_coefficients(), a, buf )[-1] )
        
        self.assertEqual( len(result), len(result2), 'Results should be equal length')
        self.assertEqual( sum([ abs( x-y ) for x,y in zip(result, result2 ) ]), 0, 'Results should be equal value')
        
    def test_notch50(self):
        """
        TODO Improve test with better timing mechanism or decouple from internal timing mechanism
        When plotting the results, the filtered signal looks really good though.
        """
        fir = FIRFilter( self.bb, self.pattern, 129, 256, 50, 'notch' )
        
        self.gen2 = DataGenerator( self.bb, '/sine', frequencies=[10], amplitudes=[1], offset=self.offset, noise=0 )
        
        self.bb.set_bufsize('/sine', 512)
        self.bb.set_bufsize('/sines/notch_50', 512)
        
        self.gen.start()
        self.gen2.start()
        fir.start()
        
        time.sleep( 3 )
        
        self.gen.stop()
        self.gen2.stop()
        fir.stop()

        time.sleep( 1 )
        
        off = len(fir.get_coefficients())
        
        target = self.bb.get_data('/sine')['data'][(off-1)/2:128+(off-1)/2]
        result = self.bb.get_data('/sines/notch_50')['data'][:128]

        #dif = np.average([ abs( x-y ) for x,y in zip(result, target ) ])
        #delta = 1
        #self.assertAlmostEqual( dif, 0, msg='Difference between target and result should be smaller than %.2f, difference is %f'%(delta,dif), delta=delta)

    def test_init_pattern_no_string(self):

        # An TypeError should be raised when a pattern is no string
        with self.assertRaises(TypeError):
            FIRFilter( self.bb, 5, 129, 256, 50, 'notch' )

    def test_init_not_implemented_filter(self):

        # An NotImplementedError should be raised
        with self.assertRaises(NotImplementedError):
            FIRFilter( self.bb, self.pattern, 129, 256, 50, 'bsf' )

    def test_init_incompatible_filter(self):

        # An TyperError should be raised
        with self.assertRaises(TypeError):
            FIRFilter( self.bb, self.pattern, 129, 256, 50, 'foo' )


    def test_init_pattern_list(self):
        # For codecoverage
        FIRFilter( self.bb, [self.pattern] , 129, 256, 50, 'notch' )
class TestFirPreprocessing(unittest.TestCase):

    def setUp(self):        
        self.bb         = Blackboard()
        self.input      = HDFReader()
    
    def create_filters(self): 
        # create preprocessing filters
        self._processors = []
        
        self.headset = 0
        self.channel = 1
        
        notch   = 50
        lowpass = 80
        
        filter_pattern1 = '/lpf%d' % ( lowpass )
        filter_pattern2 = '/notch%d' % ( notch )
        
        self.pat = '/eeg%d/channel_%d' % ( self.headset, self.channel )
        lp = IIRLowPassFilter( self.bb, [self.pat], lowpass=lowpass )
        self._processors.append( lp )
        self.pat_lpf = self.pat + filter_pattern1
        
        nf = IIRNotchFilter( self.bb, [self.pat_lpf], cutoff_freq = notch, cutoff_width=1 )
        self._processors.append( nf )
        self.pat_notch = self.pat_lpf + filter_pattern2
        
        nf = IIRNotchFilter( self.bb, [self.pat], cutoff_freq = notch, cutoff_width=1 )
        self._processors.append( nf )
        self.pat_notch1 = self.pat + filter_pattern2
        
        pp = FIRPreprocessing( self.bb, [self.pat] )
        self._processors.append( pp )
        self.pat_pp     = self.pat + '/pp'
        
    def test_start(self):
        self.create_filters()
                
        offset         = 5000
        plot_size      = 1000
        offset         = 5000
        last_count      = 0
        result         = []
        frequencies    = [1,3,5,7]
        amps           = [1,2,1,8]
        
        gen            = DataGenerator( self.bb, self.pat, frequencies=frequencies, amplitudes=amps, offset=offset, noise=0 )

        self.bb.set_bufsize( self.pat_pp, 128 )
        
        gen.start()        

        # Start filters
        for p in self._processors:
            p.start() 
        
        sleep(1)
        
        # Start processing data
        #for d in self.original[:]:
        #    self.bb.put_data( self.pat, d )
        #    local_count = self.bb.get_count( self.pat )
        #    dif = local_count - last_count
        #    if dif > 0:
        #        last_count = local_count
        #        local_results = self.bb.get_data( self.pat_pp )['data']
        #        if local_results:
        #            local_results = local_results[-dif:]
        #            for r in local_results:
        #                result.append(r)
        #    sleep(.00001)
    
        sleep(3)
        
        # Stop filters
        for p in self._processors:
            p.stop()  

        gen.stop()  
        
    def test_init_firpreprocessing_pattern_no_string(self):

        with self.assertRaises(TypeError):
            FIRPreprocessing( self.bb, 2 )

    def tearDown(self):
        unittest.TestCase.tearDown(self)
 def setUp(self):
     self.blackboard = Blackboard()
class TestBlackboard(unittest.TestCase):

    def setUp(self):
        self.blackboard = Blackboard()

    """ Test put functionality  """
    def test_put(self):
        # put value in buffer
        self.blackboard.put_data( test_pattern, test_value )
        
        # buffer should only contain the added value in a list
        self.assertEquals( self.blackboard.get_data(test_pattern)['data'], [test_value] )   
        
        # set buffersize and add a lot of data
        for pat in self.blackboard.get_patterns():
            self.blackboard.set_bufsize( pat, test_buffersize )
        for _ in range( 2000 ):
            self.blackboard.put_data( test_pattern, randint( 0, 256 ) )
            
        # check whether buffer size remains within buffersize
        self.assertEqual( len( self.blackboard.get_data( test_pattern )['data'] ), test_buffersize )
        
    """ Test get functionality """
    def test_get(self):
        # register buffer, set buffersize and add a bit of data
        for pat in self.blackboard.get_patterns():
            self.blackboard.set_bufferlength( test_buffersize )
        for _ in range( number_of_test_samples ):
            self.blackboard.put_data( test_pattern, randint( 0, 256 ) )
            
        # buffer should contain the number of added samples
        self.assertEquals( len( self.blackboard.get_data( test_pattern )['data'] ), number_of_test_samples)        
        
    def tearDown(self):
        unittest.TestCase.tearDown(self)
Esempio n. 39
0
class TestBlackboard(unittest.TestCase):
    def setUp(self):
        self.blackboard = Blackboard()

    """ Test put functionality  """

    def test_put(self):
        # put value in buffer
        self.blackboard.put_data(test_pattern, test_value)

        # buffer should only contain the added value in a list
        self.assertEquals(
            self.blackboard.get_data(test_pattern)['data'], [test_value])

        # set buffersize and add a lot of data
        for pat in self.blackboard.get_patterns():
            self.blackboard.set_bufsize(pat, test_buffersize)
        for _ in range(2000):
            self.blackboard.put_data(test_pattern, randint(0, 256))

        # check whether buffer size remains within buffersize
        self.assertEqual(len(self.blackboard.get_data(test_pattern)['data']),
                         test_buffersize)

    """ Test get functionality """

    def test_get(self):
        # register buffer, set buffersize and add a bit of data
        for pat in self.blackboard.get_patterns():
            self.blackboard.set_bufferlength(test_buffersize)
        for _ in range(number_of_test_samples):
            self.blackboard.put_data(test_pattern, randint(0, 256))

        # buffer should contain the number of added samples
        self.assertEquals(len(self.blackboard.get_data(test_pattern)['data']),
                          number_of_test_samples)

    def tearDown(self):
        unittest.TestCase.tearDown(self)
Esempio n. 40
0
 def setUp(self):
     self.blackboard = Blackboard()
Esempio n. 41
0
class TestImecInput(unittest.TestCase):
    def startUp(self):
        '''
        Helper-method for starting up headset-simulator, opening COM-port and set connection
        '''
        # Start headset-simulator
        self.hs_simulator = SerialSimulator()
        self.hs_simulator.start()

        # Get socket for serial connection
        self._socket = SerialSocket(Testing.SERIAL_PORT)

        # And pass this socket to imec
        self.imec.set_connection(self._socket)

    def setUp(self):
        self.test_pattern = 'test_eeg'
        self.test_buffer = Blackboard()
        self.imec = ImecInput(self.test_buffer, self.test_pattern)

    def tearDown(self):
        self.test_buffer.clear(self.test_pattern)


#     @unittest.skip('skip test_01')

    def test_01_init(self):
        """
        Test initalization of ImecInput
        """
        self.assertEqual(self.imec.blackboard, self.test_buffer,
                         "Blackboard not set")
        self.assertEqual(self.imec._pattern, self.test_pattern,
                         "Incorrect pattern")
        self.assertTrue(self.imec._socket == None, "Socket should not be set")

        self.assertFalse(self.imec.start('hs1'), "Start streaming should fail")
        self.assertFalse(self.imec.is_streaming(), "Should not be streaming")
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

    @patch('serial.Serial')
    def test_02_startStreaming(self, serial_mock):
        """
        Test start/stop streaming with/without connection 
        """
        self.startUp()

        serial_mock.return_value = SerialMock

        self.assertTrue(self.imec.is_connected(), "Should be connected")
        self.assertFalse(self.imec.is_streaming(),
                         "Should not be streaming yet")

        # Start streaming
        self.assertTrue(self.imec.start('hs1'), "Start streaming failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(0.2)

        self.assertFalse(self.imec.start('hs2'),
                         "Start during streaming should fail")

        self.imec.stop()
        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.hs_simulator.stop()

        self.assertFalse(self.imec.is_streaming(),
                         "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        self.imec.disconnect()
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

    @patch('serial.Serial')
    def test_03_restartAfterStop(self, serial_mock):
        self.startUp()

        serial_mock.return_value = SerialMock

        self.assertTrue(self.imec.is_connected(), "Should be connected")

        self.assertTrue(self.imec.start('hs1'), "Start streaming failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(.2)

        # Stop streaming
        self.imec.stop()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.assertFalse(self.imec.is_streaming(),
                         "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        # Restart streaming
        self.assertTrue(self.imec.start('hs2'), "Restart streaming failed")
        self.assertTrue(self.imec.is_streaming(),
                        "Not streaming after restart")

        sleep(.2)

        self.imec.stop()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.hs_simulator.stop()

        self.assertFalse(self.imec.is_streaming(),
                         "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        self.imec.disconnect()
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

    @patch('serial.Serial')
    def test_04_disconnectDuringStreaming(self, serial_mock):
        self.startUp()

        serial_mock.return_value = SerialMock

        self.assertTrue(self.imec.is_connected(), "Should be connected")

        self.assertTrue(self.imec.start('hs1'), "Start streaming failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(.2)

        # Disconnect during streaming -> streaming should stop
        self.imec.disconnect()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.assertFalse(self.imec.is_connected(), "Should be disconnected")
        self.assertFalse(self.imec.is_streaming(),
                         "Still streaming after disconnect during streaming")
        self.assertFalse(self.imec.start('hs2'),
                         "Start streaming should fail after disconnect")

        # Reconnect
        self.imec.set_connection(self._socket)
        self.assertTrue(self.imec.is_connected(), "Should be connected")
        self.assertFalse(self.imec.is_streaming(),
                         "Should not be streaming yet")

        self.assertTrue(self.imec.start('hs3'),
                        "Start streaming after reconnect failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(.2)

        self.imec.stop()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.hs_simulator.stop()

        self.assertFalse(self.imec.is_streaming(),
                         "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        self.imec.disconnect()
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

    @patch('serial.Serial')
    def test_05_parseEEG(self, serial_mock):
        """
        Test parsing EEG-data
        """
        self.startUp()

        serial_mock.return_value = SerialMock

        self.assertTrue(self.imec.is_connected(), "Should be connected")
        self.assertFalse(self.imec.is_streaming(),
                         "Should not be streaming yet")

        # Start streaming
        self.assertTrue(self.imec.start('hs1'), "Start streaming failed")
        self.assertTrue(self.imec.is_streaming(), "Should be streaming")

        sleep(.2)

        self.imec.stop()

        # Wait for thread has stopped
        while not self.imec.is_idle():
            pass

        self.hs_simulator.stop()

        self.assertFalse(self.imec.is_streaming(),
                         "Still streaming after stop")
        self.assertTrue(self.imec.is_connected(), "Should still be connected")

        self.imec.disconnect()
        self.assertFalse(self.imec.is_connected(), "Should be disconnected")

        #for ch in range(4):
        #    count = self.test_buffer.get_count(self.test_pattern + '/channel_%d' % (ch + 1))
        #    #self.assertGreater(count, 0)

        #    data = self.test_buffer.get_data(self.test_pattern + '/channel_%d' % (ch + 1), count)
        #    self.assertEqual(len(data['data']), count, "Sample-count doesn't match")
        #    self.assertEqual(len(data['timestamps']), count, "Timestamp-count doesn't match")

        #    #print 'Received %d samples on channel %d' % (count, (ch + 1))

        #    for sample, timestamp in zip(data[0], data[1]):
        #        self.assertEqual(timestamp % 0.00390625, 0.0, "Timestamp failure")
        #        self.assertGreaterEqual(sample, 0, "Sample-value too low")
        #        self.assertLessEqual(sample, 4000, "Sample-value too high")

    def test_get_battery(self):
        self.assertEqual(self.imec.get_battery(), -1)

    def test_get_duration(self):
        self.assertEqual(self.imec.get_duration(), 0)

    def test_get_serial_state(self):
        self.assertEqual(self.imec.get_serial_state(), 0)

    def test_get_port_state(self):
        self.assertEqual(self.imec.get_port_state(), 0)

    def test_get_time(self):
        self.assertEqual(self.imec.get_time(), 0)