Beispiel #1
0
 def _gaze_to_packets(self, source):
     sample_count = 0
     packet = variables_pb2.SampleVector()
     samples_per_packet = int(self.get_param("samples_per_packet"))
     for gaze_data in source:
         sample = packet.samples.add()
         sample.timestamp = int(time.time())
         sample.channels.extend(self.extract_channels(gaze_data))
         sample_count += 1
         if sample_count == samples_per_packet:
             yield packet
             packet = variables_pb2.SampleVector()
             sample_count = 0
Beispiel #2
0
    def _first_sample_data_received(self, p_data):
        """Validate p_data (is it a correct float? If not exit the program.), send it to data_proxy.
        first_sample_data_received is set to self.data_received in self.__init__, so in fact
        first_sample_data_received is fired externally by calling self.data_received"""

        # Set some additional first_sample-like data

        msg = p_data
        l_vec = variables_pb2.SampleVector()
        l_vec.ParseFromString(msg)
        self.logger.info("REAL SAMPLES PER PACKET: "+str(len(l_vec.samples)))
        for i_sample in l_vec.samples:
            self._first_sample_timestamp = i_sample.timestamp
            self.logger.info("First sample sample ts:" + repr(self._first_sample_timestamp))
            self.logger.info("First sample system ts:" + repr(time.time()))
            self.logger.info("REAL NUM OF CHANNELS:"+str(len(i_sample.channels)))
            break


            #self._first_sample_timestamp = time.time()
            #break

        self._data_proxy.set_data_len(len(p_data), self._samples_per_packet)
        self._data_proxy.set_first_sample_timestamp(self._first_sample_timestamp)
        self.logger.info("Data len: "+str(len(p_data)))
        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        # !!! below operation changes self._data_received method
        # from _first_sample_timestamp to _all_but_first_data_received

        self._data_received = self._all_but_first_data_received
        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        self._data_received(p_data)
Beispiel #3
0
    def handle_message(self, mxmsg):
        #always buffer signal
        if mxmsg.type == types.AMPLIFIER_SIGNAL_MESSAGE:
            l_msg = variables_pb2.SampleVector()
            l_msg.ParseFromString(mxmsg.message)
            #Supply buffer with sample data, the buffer will fire its
            #ret_func (that we defined as self.analysis.analyse) every 'every' samples
            self.buffer.handle_sample_vect(l_msg)
            if DEBUG:
                self.debug.next_sample()

        #process blinks only when hold_time passed
        if self._last_dec_time > 0:
            t = time.time() - self._last_dec_time
            if t > self.hold_after_dec:
                self._last_dec_time = 0
                ugm_helper.send_start_blinking(self.conn)
            else:
                self.no_response()
                return

        if mxmsg.type == types.BLINK_MESSAGE:
            l_msg = variables_pb2.Blink()
            l_msg.ParseFromString(mxmsg.message)
            self.buffer.handle_blink(l_msg)
            
        self.no_response()
Beispiel #4
0
 def _create_msg(self, samples):
     assert (self.samples_per_packet == len(samples))
     v = variables_pb2.SampleVector()
     for sample, ts in samples:
         s = v.samples.add()
         s.channels.extend(sample)
         s.timestamp = ts
     return v
 def _samples_callback(self, params):
     self.collected_samples.append((params[0], params[1]))
     if len(self.collected_samples) == self.samples_per_packet:
         v = variables_pb2.SampleVector()
         for ts, sample in self.collected_samples:
             s = v.samples.add()
             s.channels.extend(sample)
             s.timestamp = ts
         self.collected_samples = []
         self._send(self._create_mx_msg(v))
 def handle_message(self, mxmsg):
     if mxmsg.type == self.in_mx_signal_type:
         v = variables_pb2.SampleVector()
         v.ParseFromString(mxmsg.message)
         for s in v.samples:
             msg = self.get_msg(s)
             self.conn.send_message(message=msg.SerializeToString(),
                                    type=self.out_mx_signal_type,
                                    flush=True)
             print msg
     self.no_response()
Beispiel #7
0
 def handle_message(self, mxmsg):
     if mxmsg.type == self.in_mx_signal_type:
         v = variables_pb2.SampleVector()
         v.ParseFromString(mxmsg.message)
         for s in v.samples:
             msg = variables_pb2.Sample2D()
             msg.x = s.channels[self.x_ind]
             msg.y = s.channels[self.y_ind]
             msg.timestamp = s.timestamp
             self.conn.send_message(
                     message=msg.SerializeToString(),
                     type=self.out_mx_signal_type, flush=True)
     self.no_response()
    def handle_message(self, mxmsg):
        if mxmsg.type == types.AMPLIFIER_SIGNAL_MESSAGE:
            if DEBUG:
                self.debug.next_sample()
            msg = mxmsg.message
            l_vec = variables_pb2.SampleVector()
            l_vec.ParseFromString(msg)
            self.logger.debug("Got pack of samples in moment: "+str(time.time()))
            for i_sample in l_vec.samples:
                diff = time.time()-i_sample.timestamp
                comm = ''.join([
                        "Sample ts: ", str(i_sample.timestamp),
                        " / Real ts:"+str(time.time()),
                        " / "+"DIFF: "+str(diff)])
                self.logger.debug(comm)
                if diff > 0.1:
                    self.logger.error(comm+"\n\n")
                if self.amp_saw_ind >= 0:
                    v = i_sample.channels[self.amp_saw_ind]
                    if self._amp_saw_last + self.amp_saw_step - v > 0:
                        self.logger.error("Last: "+str(self._amp_saw_last)+" Amp saw: "+str(v))
                        self.logger.error(''.join(["LOOOOOOOOST AMPLIFIER SAMPLES, sth like: ",
                                              str(self._amp_saw_last + self.amp_saw_step - v),
                                              " samples!!!"
                                              ])+"\n\n")

                    if v == self.amp_saw_max:
                        self._amp_saw_last = -self.amp_saw_step + 1
                    else:
                        self._amp_saw_last = v
                    self.logger.debug("Amp saw: "+str(v))
                if self.driver_saw_ind >= 0:
                    v = i_sample.channels[self.driver_saw_ind]
                    if self._driver_saw_last + self.driver_saw_step - v > 0:
                        self.logger.error("Last: "+str(self._driver_saw_last)+" Driver saw: "+str(v))
                        self.logger.error(''.join(["LOOOOOOOOST DRIVER SAMPLES, sth like: ",
                                              str(self._driver_saw_last + self.driver_saw_step - v),
                                              " samples!!!"
                                              ])+"\n\n")

                    if v == self.driver_saw_max:
                        self._driver_saw_last = -self.driver_saw_step + 1
                    else:
                        self._driver_saw_last = v
                    self.logger.debug("Driver saw: "+str(v))
                self.logger.debug("First channel value: "+str(i_sample.channels[0]))
        else:
            self.logger.error("Got unrecognised message!!!")
        self.no_response()
 def handle_message(self, mxmsg):
     if mxmsg.type == self.in_mx_signal_type:
         v = variables_pb2.SampleVector()
         v.ParseFromString(mxmsg.message)
         for s in v.samples:
             msg = variables_pb2.Sample2D()
             x, y = wii_utils.get_x_y(s.channels[0], s.channels[1],
                                      s.channels[2], s.channels[3])
             msg.x = 0.5 - x * 0.5
             msg.y = 0.5 - y * 0.5
             msg.timestamp = s.timestamp
             self.conn.send_message(message=msg.SerializeToString(),
                                    type=self.out_mx_signal_type,
                                    flush=True)
     self.no_response()
Beispiel #10
0
    def handle_message(self, mxmsg):
        """The only required function in the class
        that will be fired every time message is received"""
        if mxmsg.type == types.AMPLIFIER_SIGNAL_MESSAGE:
            # Got proper message, let`s unpack it ...

            # Messages are transmitted in bunches so lets define SampleVector
            # in order to unpack bunch of Sample messages ...
            l_vect = variables_pb2.SampleVector()
            l_vect.ParseFromString(mxmsg.message)

            # Now we have message unpacked, lets iterate over every sample ...
            for s in l_vect.samples:

                # Every sample has two fields:
                # timestamp - system clock time of a moment of Sample`s creation
                # channels - a list of values - one for every channel
                self.logger.debug("Got sample with timestamp: " +
                                  str(s.timestamp))

                # One can copy samples to numpy array ...
                a = numpy.array(s.channels)

                # Or just iterate over values ...
                for ch in s.channels:
                    self.logger.debug(ch)

        # Having a new bunch of values one can fire some magic analysis and
        # generate decision ....

        # Below we have quite simple decision-maker - it generates a random
        # decision every ~100 samples-bunch
            if random.random() > 0.99:
                # Here we send DECISION message somewhere-to-the-system ...
                # It's up to scenario's configuration how the decision will be used ...
                # Eg. it might be used by LOGIC module to push some button in speller.
                msg = str(random.randint(0, 7))
                self.logger.info("Send random message in analysis... " + msg)
                self.conn.send_message(message=msg,
                                       type=types.DECISION_MESSAGE,
                                       flush=True)
        else:
            self.logger.warning("Got unrecognised message type: " +
                                str(mxmsg.type))

        # Tell the system 'I`ll not respond to this message, I`m just receiving'
        self.no_response()
    def handle_message(self, mxmsg):
        if mxmsg.type == types.WII_BOARD_SIGNAL_MESSAGE:
            if self._dummy:
                sway_direction, sway_level = self._calculate_dummy_sway()
            else:
                #calculate and send current sway direction and level
                v = variables_pb2.SampleVector()
                v.ParseFromString(mxmsg.message)
                X, Y = [], []
                for s in v.samples:  #todo - refactor in regard to utils/wii_2d_router
                    sum_mass = sum(s.channels[0:4])
                    if sum_mass < 200:
                        break
                    x, y = wii_utils.get_x_y(s.channels[0], s.channels[1],
                                             s.channels[2], s.channels[3])
                    X.append(x)
                    Y.append(y)
                if len(X):
                    sway_direction, sway_level = self._calculate_real_sway(
                        np.mean(X), np.mean(Y))
                else:
                    sway_direction, sway_level = 'baseline', 0

            msg = variables_pb2.IntVariable()
            msg.key = sway_direction
            msg.value = sway_level
            self.conn.send_message(message=msg.SerializeToString(),
                                   type=types.WII_BOARD_ANALYSIS_RESULTS,
                                   flush=True)
        elif mxmsg.type == types.ACQUISITION_CONTROL_MESSAGE:
            # storing user's current maxes makes sens only in calibration scenario ...
            if self._session_name not in [
                    'ventures_calibration', 'sway_with_feedback'
            ]:
                self.logger.info(
                    "Got acquisition_control_message, but session name is " +
                    self._session_name + " . Just exit quietly ...")
                sys.exit(0)
            else:  #self._session_name == 'ventures_calibration'
                self.logger.info(
                    "Got acquisition_control_message in calibration session. Start storing calibration results (maxes)... "
                )
                self._store_calibration_results()
                sys.exit(0)
        else:
            self.logger.warning("Unrecognised message type!!!")
        self.no_response()
def get_sample_vector(per, ch_num, ts_step):
    """generate signal like:
    [ [1,2,3,4,5....
      [10,20,30,40,50...
      [100,200,300, ...
    ...
    ]
    """
    global COUNT
    sample_vector = variables_pb2.SampleVector()
    for x in range(per):
        COUNT += 1
        samp = sample_vector.samples.add()
        for j in range(ch_num):
            samp.channels.append((10**(j)) * COUNT)
        #print(samp.channels[0])
        samp.timestamp = time.time()
        time.sleep(ts_step)
    return sample_vector
Beispiel #13
0
    def handle_message(self, mxmsg):
        if self._last_dec_time > 0:
            t = time.time() - self._last_dec_time
            if t > self.hold_after_dec:
                self._last_dec_time = 0
            else:
                if mxmsg.type == types.AMPLIFIER_SIGNAL_MESSAGE and DEBUG:
                    self.debug.next_sample()
                self.no_response()
                return

        if mxmsg.type == types.AMPLIFIER_SIGNAL_MESSAGE:
            l_msg = variables_pb2.SampleVector()
            l_msg.ParseFromString(mxmsg.message)
            #Supply buffer with sample data, the buffer will fire its
            #ret_func (that we defined as self.analysis.analyse) every 'every' samples
            self.buffer.handle_sample_vect(l_msg)
            if DEBUG:
                self.debug.next_sample()
        self.no_response()
    def received_message(self, m):

        msg = json.loads(str(m))
        timestamp = float(msg['timestamp'])
        sample = self.msg_vector.samples.add()
        sample.timestamp = timestamp
        try:
            sample.channels.extend(float(msg[i]) for i in self.peer.chs)
        except KeyError as e:
            unavailable_channels_set = set(self.peer.chs).difference(
                set(msg.keys()))
            unavailable_channels_msg = ', '.join(unavailable_channels_set)
            msg = '''
            
            ERROR: UNAVAILABLE CHANNELS:
            {unavailable_channels}
            
            
            Channels from tracker server JSON:
            {available_channels}
            

            You've tried to access channels:
            
            {requested_channels}
            
            
            
            '''.format(
                unavailable_channels=unavailable_channels_msg,
                available_channels=', '.join(msg.keys()),
                requested_channels=', '.join(self.peer.chs),
            )

            self.peer.logger.error(msg)
            raise KeyError(unavailable_channels_msg)

        if len(self.msg_vector.samples) == self.samples_per_packet:
            #send when big enough and create new empty vector
            self.peer.process_message(self.msg_vector)
            self.msg_vector = variables_pb2.SampleVector()
    def _vect_to_string(self, p_mx_vect):
        l_vec = variables_pb2.SampleVector()
        l_vec.ParseFromString(p_mx_vect)
        samples = []
        for j in range(len(l_vec.samples)):
            s = l_vec.samples[j]
            ts = s.timestamp
            try:
                strs = [
                    struct.pack(self._sample_struct_type, ch)
                    for ch in s.channels
                ]
                if self._append_ts:
                    strs.append(struct.pack(self._sample_struct_type, ts))
            except struct.error:
                LOGGER.error(
                    "Error while writhing to file. Bad sample format.")
                raise (signal_exceptions.BadSampleFormat())

            samples.append(''.join(strs))
        return ''.join(samples)
Beispiel #16
0
    def handle_message(self, mxmsg):
        """Internal method, fired every time message is received.

        Args:
            mxmsg: message data
        """
        if mxmsg.type == types.AMPLIFIER_SIGNAL_MESSAGE:
            # we have received part of the signal
            data = variables_pb2.SampleVector()
            data.ParseFromString(mxmsg.message)
            self.buffer.handle_sample_vect(data)

        elif mxmsg.type == types.BLINK_MESSAGE:
            # we have received a single blink
            data = variables_pb2.Blink()
            data.ParseFromString(mxmsg.message)
            self.buffer.handle_blink(data)

        else:
            self.logger.warning("Got unrecognised message type: " +
                                str(mxmsg.type))
        self.no_response()
 def __init__(self, url, peer, samples_per_packet=4):
     super(EtrWebSocketClient, self).__init__(url, )
     self.peer = peer
     self.samples_per_packet = samples_per_packet
     self.msg_vector = variables_pb2.SampleVector()