示例#1
0
class NSDataReaderRandom(object):
    def __init__(self):
        self.ch_num = 8
        self.signal = []
        self.data_time = []
        self.fs = 500  # 数据生成速度无法达到500采样
        self.repeat_timer = RepeatingTimer(0.1, self._read_data)

    def start(self):
        self.repeat_timer.start()

    def _read_data(self):
        data = (10 * np.random.randn(400)).tolist()
        self.signal += [
            data[i:i + self.ch_num] for i in range(0, len(data), self.ch_num)
        ]
        self.data_time.append(time())

    def get_ns_signal(self, duration=None):
        signal = np.array(self.signal)
        return signal[-duration:,
                      0:-1] if duration else signal[:, 0:
                                                    -1]  # remove label column

    def get_head_settings(self):
        return {
            'sample_rate': self.fs,
            'channel_list':
            ['FP1', 'FPz', 'FP2', 'AF3', 'AF4', 'F5', 'F3', 'F1']
        }
示例#2
0
 def __init__(self):
     # self.address = '192.168.11.123', 9889  # 有线
     # self.address = '10.168.2.164', 9889  # QAAS_Bridge wifi
     self.address = '192.168.43.166', 9889
     self.socket = socket.socket()
     self.socket.settimeout(15)
     self.repeat_timer = RepeatingTimer(0.02, self._read_data)  # 循环时间应<0.02
     self.signal = []
     self.data_time = []
     self.count = 0
     self.endTime = 0
示例#3
0
 def __init__(self):
     self.is_playing = False
     self.vol = config.app["main"]["volume"]
     self.is_working = False
     self.queue = []
     self.stopped = True
     self.queue_pos = 0
     self.shuffle = False
     self.worker = RepeatingTimer(5, self.player_function)
     self.worker.start()
     self.output = output.Output()
     self.set_output_device(config.app["main"]["output_device"])
     self.player = None
示例#4
0
    def calculate_sharpness_video_capture(
            self,
            cv_video_capture: CVVideoCapture,
            frame_start=0,
            frame_end=None,
            batch_size=200,
            gray_scale_conversion_code=cv2.COLOR_BGR2GRAY,
            progress_tracker: CVProgressTracker = None):
        frame_count = int(cv_video_capture.get_frame_count())
        if frame_end:
            cv_video_capture.set_position_frame(frame_start)
            frame_count = min(frame_end - frame_start, frame_count)
            frame_count = max(frame_count, 0)

        if progress_tracker:
            progress_tracker.running = True

        frame_sharpness_ctype = multiprocessing.Array('d', frame_count)
        progress_value = multiprocessing.Value('d')
        progress_value.value = 0
        lock_video_capture = RLock()

        worker_count = multiprocessing.cpu_count()
        task_per_worker = int(frame_count / worker_count)
        args_list = [
            (task_per_worker * i, task_per_worker * (i + 1), frame_start,
             frame_count, batch_size, self.kernel_x, self.kernel_y,
             frame_sharpness_ctype, cv_video_capture.file_handle,
             progress_value, lock_video_capture, gray_scale_conversion_code)
            for i in range(0, worker_count - 1)
        ]
        args_list.append(
            (task_per_worker * (worker_count - 1), frame_count, frame_start,
             frame_count, batch_size, self.kernel_x, self.kernel_y,
             frame_sharpness_ctype, cv_video_capture.file_handle,
             progress_value, lock_video_capture, gray_scale_conversion_code))

        processes = [
            Process(target=_calculate_sharpness_video_capture_worker,
                    args=arg_tuple) for arg_tuple in args_list
        ]

        def update_progress_tracker():
            progress_tracker.progress = progress_value.value

        progress_timer = RepeatingTimer(0.5, update_progress_tracker)

        if progress_tracker:
            progress_timer.start()

        if progress_tracker:
            progress_tracker.running = True
        for p in processes:
            p.start()
        for p in processes:
            p.join()
        if progress_tracker:
            progress_timer.cancel()
            progress_tracker.complete()
        return np.array(frame_sharpness_ctype)
示例#5
0
class NSDataReader(object):
    def __init__(self):
        # self.address = '192.168.11.123', 9889  # 有线
        # self.address = '10.168.2.164', 9889  # QAAS_Bridge wifi
        self.address = '192.168.43.166', 9889
        self.socket = socket.socket()
        self.socket.settimeout(15)
        self.repeat_timer = RepeatingTimer(0.02, self._read_data)  # 循环时间应<0.02
        self.signal = []
        self.data_time = []
        self.count = 0
        self.endTime = 0

    def start(self):
        self.socket.connect(self.address)
        self._read_header()
        self.repeat_timer.start()

    def _read_header(self):
        self._send_command_to_ns(3, 5)
        sleep(0.1)
        # get basic information
        self.BasicInfo = self.socket.recv(1024)
        code = int.from_bytes(self.BasicInfo[4:6], byteorder='big')
        req = int.from_bytes(self.BasicInfo[6:8], byteorder='big')
        size = int.from_bytes(self.BasicInfo[8:12], byteorder='big')
        if code == 1 and req == 3 and size == 28 and len(self.BasicInfo) == 40:
            # self.Bsize = int.from_bytes(self.BasicInfo[12:16], byteorder='little')
            # self.BEegChannelNum = int.from_bytes(self.BasicInfo[16:20], byteorder='little')
            # self.BEventChannelNum = int.from_bytes(self.BasicInfo[20:24], byteorder='little')
            # self.BlockPnts = int.from_bytes(self.BasicInfo[24:28], byteorder='little')
            # self.BSampleRate = int.from_bytes(self.BasicInfo[28:32], byteorder='little')
            # self.BDataSize = int.from_bytes(self.BasicInfo[32:36], byteorder='little')
            # self.BResolution = struct.unpack('<f', self.BasicInfo[36:40])[0]
            (self.Bsize, self.BEegChannelNum, self.BEventChannelNum,
             self.BlockPnts, self.BSampleRate, self.BDataSize,
             self.BResolution) = struct.unpack_from('<iiiiiif', self.BasicInfo,
                                                    12)
            self.pattern = '<h' if self.BDataSize == 2 else '<i'
            self.ch_num = self.BEegChannelNum + self.BEventChannelNum
            # self.T = self.BlockPnts / self.BSampleRate / 2
        self._send_command_to_ns(2, 1)
        self._send_command_to_ns(3, 3)

    def _read_data(self):
        while True:
            data_head = self.socket.recv(12)
            if len(data_head) != 0:
                break
        size = int.from_bytes(data_head[8:12], byteorder='big')
        data = bytearray()
        while len(data) < size:
            data += self.socket.recv(size - len(data))
        data = [
            i[0] * self.BResolution
            for i in struct.iter_unpack(self.pattern, data)
        ]
        self.signal += [
            data[i:i + self.ch_num] for i in range(0, len(data), self.ch_num)
        ]
        self.data_time.append(time())

    def stop_data_reader(self):
        self._send_command_to_ns(3, 4)
        self._send_command_to_ns(2, 2)
        self._send_command_to_ns(1, 2)
        sleep(0.1)
        self.repeat_timer.cancel()
        self.socket.close()

    def get_ns_signal(self, duration=None):
        signal = np.array(self.signal)
        return signal[-duration:,
                      0:-1] if duration else signal[:, 0:
                                                    -1]  # remove label column

    def get_head_settings(self):
        channel_list = [
            'FP1', 'FPz', 'FP2', 'AF3', 'AF4', 'F5', 'F3', 'F1', 'Fz', 'F2',
            'F4', 'F6', 'FC5', 'FC3', 'FC1', 'FCz', 'FC2', 'FC4', 'FC6', 'C5',
            'C3', 'C1', 'Cz', 'C2', 'C4', 'C6', 'CP5', 'CP3', 'CP1', 'CPz',
            'CP2', 'CP4', 'CP6', 'M1', 'M2'
        ]  # 35 ch
        return {'sample_rate': self.BSampleRate, 'channel_list': channel_list}

    def _send_command_to_ns(self, ctrcode, reqnum):
        a = 'CTRL'
        cmd = a.encode(encoding="utf-8")
        cmd += ctrcode.to_bytes(2, 'big')
        cmd += reqnum.to_bytes(2, 'big')
        cmd += (0).to_bytes(4, 'big')
        self.socket.sendall(cmd)
示例#6
0
 def __init__(self):
     self.ch_num = 8
     self.signal = []
     self.data_time = []
     self.fs = 500  # 数据生成速度无法达到500采样
     self.repeat_timer = RepeatingTimer(0.1, self._read_data)
示例#7
0
    def test_optical_flow_video_capture(
            self,
            cv_video_capture: CVVideoCapture,
            distance_limit,
            frame_acceptance_np: np.ndarray,
            frame_start=0,
            frame_end=None,
            batch_size=200,
            gray_scale_conversion_code=cv2.COLOR_BGR2GRAY,
            progress_tracker: CVProgressTracker = None):
        frame_count = int(cv_video_capture.get_frame_count())
        if frame_end:
            cv_video_capture.set_position_frame(frame_start)
            frame_count = min(frame_end - frame_start, frame_count)
            frame_count = max(frame_count, 0)

        if progress_tracker:
            progress_tracker.running = True

        frame_acceptance_ctype = \
            multiprocessing.Array('b', frame_acceptance_np.tolist())

        progress_value = multiprocessing.Value('d')
        progress_value.value = 0
        lock_video_capture = multiprocessing.RLock()

        skip_window_both_end = int(cv_video_capture.get_frame_rate())
        # worker_count = 1
        worker_count = multiprocessing.cpu_count()
        task_per_worker = int(frame_count / worker_count)
        args_list = [
            (task_per_worker * i, task_per_worker * (i + 1), frame_start,
             frame_count, batch_size, distance_limit, self.feature_params,
             self.lucas_kanade_params, frame_acceptance_ctype,
             cv_video_capture.file_handle, progress_value, lock_video_capture,
             gray_scale_conversion_code, skip_window_both_end)
            for i in range(0, worker_count - 1)
        ]
        args_list.append(
            (task_per_worker * (worker_count - 1), frame_count, frame_start,
             frame_count, batch_size, distance_limit, self.feature_params,
             self.lucas_kanade_params, frame_acceptance_ctype,
             cv_video_capture.file_handle, progress_value, lock_video_capture,
             gray_scale_conversion_code, skip_window_both_end))

        processes = [
            Process(target=_test_optical_flow_capture_worker, args=arg_tuple)
            for arg_tuple in args_list
        ]

        def update_progress_tracker():
            progress_tracker.progress = progress_value.value / worker_count * 0.7

        progress_timer = RepeatingTimer(0.1, update_progress_tracker)

        if progress_tracker:
            progress_timer.start()

        if progress_tracker:
            progress_tracker.running = True
        for p in processes:
            p.start()
        for p in processes:
            p.join()

        print('[OpticalFlow] final pass')

        final_pass_ranges = generate_multiprocessing_final_pass_ranges \
            (frame_acceptance_ctype, frame_count, task_per_worker, worker_count, skip_window_both_end)

        final_pass_arg_list = [
            (range_i[0], range_i[1], frame_start, frame_count, batch_size,
             distance_limit, self.feature_params, self.lucas_kanade_params,
             frame_acceptance_ctype, cv_video_capture.file_handle,
             progress_value, lock_video_capture, gray_scale_conversion_code)
            for range_i in final_pass_ranges
        ]

        final_pass_processes = [
            Process(target=_test_optical_flow_capture_worker, args=arg_tuple)
            for arg_tuple in final_pass_arg_list
        ]

        def update_progress_tracker_final_pass():
            progress_tracker.progress = 0.7 + progress_value.value / worker_count * 0.3

        progress_value.value = 0
        if progress_tracker:
            progress_timer.function = update_progress_tracker_final_pass

        for p in final_pass_processes:
            p.start()
            # for p in final_pass_processes:
            p.join()

        if progress_tracker:
            progress_timer.cancel()
            progress_tracker.complete()

        return np.array(frame_acceptance_ctype, dtype=np.bool_).copy()
        pass
示例#8
0
class audioPlayer(object):
    def __init__(self):
        self.is_playing = False
        self.vol = config.app["main"]["volume"]
        self.is_working = False
        self.queue = []
        self.stopped = True
        self.queue_pos = 0
        self.shuffle = False
        self.worker = RepeatingTimer(5, self.player_function)
        self.worker.start()
        self.output = output.Output()
        self.set_output_device(config.app["main"]["output_device"])
        self.player = None

    def get_output_devices(self):
        """ Retrieve enabled output devices so we can switch or use those later. """
        devices = output.Output.get_device_names()
        return devices

    def set_output_device(self, device_name):
        """ Set Output device to be used in LibVLC"""
        log.debug("Setting output audio device to {device}...".format(
            device=device_name, ))
        try:
            self.output.set_device(
                self.output.find_device_by_name(device_name))
        except:
            log.error("Error in input or output devices, using defaults...")
            config.app["main"]["output_device"] = "Default"

    def play(self, item):
        self.stopped = True
        if self.is_working == False:
            self.is_working = True
            if item.download_url == "":
                item.get_download_url()
            log.debug("playing {0}...".format(item.download_url, ))
            if hasattr(self, "player"
                       ) and self.player != None and self.player.is_playing:
                self.player.stop()
            self.player = stream.URLStream(item.download_url)
            if self.player.play() == -1:
                log.debug("Error when playing the file {0}".format(
                    item.title, ))
                pub.sendMessage("change_status",
                                status=_("Error playing {0}. {1}.").format(
                                    item.title, e.description))
                self.stopped = True
                self.is_working = False
                self.next()
                return
            self.player.volume = self.vol / 100
            pub.sendMessage("change_status",
                            status=_("Playing {0}.").format(item.title))
            self.stopped = False
            self.is_working = False

    def next(self):
        if len(self.queue) > 0:
            if self.shuffle:
                self.queue_pos = random.randint(0, len(self.queue) - 1)
            else:
                if self.queue_pos < len(self.queue) - 1:
                    self.queue_pos += 1
                else:
                    self.queue_pos = 0
            self.play(self.queue[self.queue_pos])

    def previous(self):
        if len(self.queue) > 0:
            if self.shuffle:
                self.queue_pos = random.randint(0, len(self.queue) - 1)
            else:
                if self.queue_pos > 0:
                    self.queue_pos -= 1
                else:
                    self.queue_pos = len(self.queue) - 1
            self.play(self.queue[self.queue_pos])

    def stop(self):
        self.player.stop()
        self.stopped = True

    def pause(self):
        self.player.pause()
        if self.stopped == True:
            self.stopped = False
        else:
            self.stopped = True

    @property
    def volume(self):
        return self.vol

    @volume.setter
    def volume(self, vol):
        if vol <= 100 and vol >= 0:
            config.app["main"]["volume"] = vol
            self.vol = vol
        if self.player != None:
            self.player.volume = self.vol / 100

    def play_all(self, list_of_items, playing=0, shuffle=False):
        if list_of_items != self.queue:
            self.queue = list_of_items
        self.shuffle = shuffle
        self.queue_pos = playing
        self.play(self.queue[self.queue_pos])

    def player_function(self):
        """ Check if the stream has reached the end of the file  so it will play the next song. """
        if self.player != None and self.player.is_playing == False and self.stopped == False and len(
                self.player) - self.player.position < 50000:

            if self.queue_pos >= len(self.queue):
                self.stopped = True
                return
            elif self.queue_pos < len(self.queue):
                self.queue_pos += 1
            self.play(self.queue[self.queue_pos])

    def playback_error(self, event):
        pub.sendMessage(
            "notify",
            title=_("Error"),
            message=
            _("There was an error while trying to access the file you have requested."
              ))