Exemplo n.º 1
0
    def build(self) -> osc_message.OscMessage:
        """Builds an OscMessage from the current state of this builder.

        Raises:
          - BuildError: if the message could not be build or if the address
                        was empty.

        Returns:
          - an osc_message.OscMessage instance.
        """
        if not self._address:
            raise BuildError('OSC addresses cannot be empty')
        dgram = b''
        try:
            # Write the address.
            dgram += osc_types.write_string(self._address)
            if not self._args:
                dgram += osc_types.write_string(',')
                return osc_message.OscMessage(dgram)

            # Write the parameters.
            arg_types = "".join([arg[0] for arg in self._args])
            dgram += osc_types.write_string(',' + arg_types)
            for arg_type, value in self._args:
                if arg_type == self.ARG_TYPE_STRING:
                    dgram += osc_types.write_string(value)
                elif arg_type == self.ARG_TYPE_INT:
                    dgram += osc_types.write_int(value)
                elif arg_type == self.ARG_TYPE_INT64:
                    dgram += osc_types.write_int64(value)
                elif arg_type == self.ARG_TYPE_FLOAT:
                    dgram += osc_types.write_float(value)
                elif arg_type == self.ARG_TYPE_DOUBLE:
                    dgram += osc_types.write_double(value)
                elif arg_type == self.ARG_TYPE_BLOB:
                    dgram += osc_types.write_blob(value)
                elif arg_type == self.ARG_TYPE_RGBA:
                    dgram += osc_types.write_rgba(value)
                elif arg_type == self.ARG_TYPE_MIDI:
                    dgram += osc_types.write_midi(value)
                elif arg_type in (self.ARG_TYPE_TRUE,
                                  self.ARG_TYPE_FALSE,
                                  self.ARG_TYPE_ARRAY_START,
                                  self.ARG_TYPE_ARRAY_STOP,
                                  self.ARG_TYPE_NIL):
                    continue
                else:
                    raise BuildError('Incorrect parameter type found {}'.format(
                        arg_type))

            return osc_message.OscMessage(dgram)
        except osc_types.BuildError as be:
            raise BuildError('Could not build the message: {}'.format(be))
Exemplo n.º 2
0
 def test_all_non_standard_params(self):
     msg = osc_message.OscMessage(_DGRAM_ALL_NON_STANDARD_TYPES_OF_PARAMS)
     self.assertEqual("/SYNC", msg.address)
     self.assertEqual(2, len(msg.params))
     self.assertEqual(True, msg.params[0])
     self.assertEqual(False, msg.params[1])
     self.assertEqual(2, len(list(msg)))
Exemplo n.º 3
0
    def _parse_contents(self, index: int) -> Any:
        contents = []

        try:
            # An OSC Bundle Element consists of its size and its contents.
            # The size is an int32 representing the number of 8-bit bytes in the
            # contents, and will always be a multiple of 4. The contents are either
            # an OSC Message or an OSC Bundle.
            while self._dgram[index:]:
                # Get the sub content size.
                content_size, index = osc_types.get_int(self._dgram, index)
                # Get the datagram for the sub content.
                content_dgram = self._dgram[index:index + content_size]
                # Increment our position index up to the next possible content.
                index += content_size
                # Parse the content into an OSC message or bundle.
                if OscBundle.dgram_is_bundle(content_dgram):
                    contents.append(OscBundle(content_dgram))
                elif osc_message.OscMessage.dgram_is_message(content_dgram):
                    contents.append(osc_message.OscMessage(content_dgram))
                else:
                    logging.warning(
                        "Could not identify content type of dgram %s" %
                        content_dgram)
        except (osc_types.ParseError, osc_message.ParseError, IndexError) as e:
            raise ParseError("Could not parse a content datagram: %s" % e)

        return contents
Exemplo n.º 4
0
    def __init__(self, dgram):
        """Initialize an OdpPacket with the given UDP datagram.

    Args:
      - dgram: the raw UDP datagram holding the OSC packet.

    Raises:
      - ParseError if the datagram could not be parsed.
    """
        now = time.time()  #calendar.timegm(time.gmtime())
        try:
            if osc_bundle.OscBundle.dgram_is_bundle(dgram):
                #bund=osc_bundle.OscBundle(dgram)
                self._messages = sorted(_timed_msg_of_bundle(
                    osc_bundle.OscBundle(dgram), now),
                                        key=lambda x: x.time)
            elif osc_message.OscMessage.dgram_is_message(dgram):
                self._messages = (TimedMessage(
                    now, osc_message.OscMessage(dgram)), )
            else:
                # Empty packet, should not happen as per the spec but heh, UDP...
                raise ParseError(
                    'OSC Packet should at least contain an OscMessage or an '
                    'OscBundle.')
        except (osc_bundle.ParseError, osc_message.ParseError) as pe:
            raise ParseError('Could not parse packet %s' % pe)
Exemplo n.º 5
0
 def test_complex_array_params(self):
     msg = osc_message.OscMessage(_DGRAM_COMPLEX_ARRAY_PARAMS)
     self.assertEqual("/SYNC", msg.address)
     self.assertEqual(3, len(msg.params))
     self.assertEqual([1], msg.params[0])
     self.assertEqual([["ABC", "DEF"]], msg.params[1])
     self.assertEqual([[2], [3, ["GHI"]]], msg.params[2])
     self.assertEqual(3, len(list(msg)))
Exemplo n.º 6
0
 def recv(self, dgram_size=1024, timeout=1):
     '''Receive UDP OSC message from SC'''
     ready = select.select([self._sock], [], [], timeout)[0]
     if ready:
         dgram = self._sock.recv(dgram_size)
         msg = osc_message.OscMessage(dgram)
         return msg.params
     raise TimeoutError('socket timeout when receiving data from SC')
Exemplo n.º 7
0
 def test_all_standard_types_off_params(self):
     msg = osc_message.OscMessage(_DGRAM_ALL_STANDARD_TYPES_OF_PARAMS)
     self.assertEqual("/SYNC", msg.address)
     self.assertEqual(4, len(msg.params))
     self.assertEqual(3, msg.params[0])
     self.assertAlmostEqual(2.0, msg.params[1])
     self.assertEqual("ABC", msg.params[2])
     self.assertEqual(b"stuff\x00\x00\x00", msg.params[3])
     self.assertEqual(4, len(list(msg)))
Exemplo n.º 8
0
    def test_all_non_standard_params(self):
        msg = osc_message.OscMessage(_DGRAM_ALL_NON_STANDARD_TYPES_OF_PARAMS)

        self.assertEqual("/SYNC", msg.address)
        self.assertEqual(5, len(msg.params))
        self.assertEqual(True, msg.params[0])
        self.assertEqual(False, msg.params[1])
        self.assertEqual([], msg.params[2])
        self.assertEqual((datetime(1900, 1, 1, 0, 0, 0), 0), msg.params[3])
        self.assertEqual(1000000000000, msg.params[4])
        self.assertEqual(5, len(list(msg)))
Exemplo n.º 9
0
 def process(self, data, sender):
     now = time.time()
     # TODO exception handling
     if osc_bundle.OscBundle.dgram_is_bundle(data):
         bundle = osc_bundle.OscBundle(data)
         self.process_bundle(bundle, now, sender)
         return True
     elif osc_message.OscMessage.dgram_is_message(data):
         msg = osc_message.OscMessage(data)
         self.queue.put(([msg], now, sender))
         return True
     else:
         return False
Exemplo n.º 10
0
def process(dgram):
    """Process datagram to OSC bundle or message."""
    try:
        if osc_bundle.OscBundle.dgram_is_bundle(dgram):
            bundle = osc_bundle.OscBundle(dgram)
            if bundle.num_contents != 1 or \
               not isinstance(bundle.content(0), osc_message.OscMessage):
                raise ValueError("XIO OSC bundle should contain"
                                 "a single OSC message.")
            return bundle
        elif osc_message.OscMessage.dgram_is_message(dgram):
            return osc_message.OscMessage(dgram)
        else:
            # Empty packet, should not happen as per the spec but heh, UDP...
            raise ParseError("Datagram should at least contain"
                             "an OscMessage or an OscBundle.")
    except (osc_bundle.ParseError, osc_message.ParseError) as error:
        raise ParseError("Could not parse packet {:s}".format(error))
Exemplo n.º 11
0
  def build_dgram(self):
    """Builds an OscMessage datagram from the current state of this builder.

    Raises:
      - BuildError: if the message could not be build or if the address
                    was empty.

    Returns:
      - an osc_message.OscMessage instance.
    """
    if not self._address:
      raise BuildError('OSC addresses cannot be empty')
    dgram = b''
    try:
      # Write the address.
      dgram += osc_types.write_string(self._address)
      if not self._args:
        dgram += osc_types.write_string(',')
        return osc_message.OscMessage(dgram)

      # Write the parameters.
      arg_types = "".join([arg[0] for arg in self._args])
      dgram += osc_types.write_string(',' + arg_types)
      for arg_type, value in self._args:
        if arg_type == self.ARG_TYPE_STRING:
          dgram += osc_types.write_string(value)
        elif arg_type == self.ARG_TYPE_INT:
          dgram += osc_types.write_int(value)
        elif arg_type == self.ARG_TYPE_FLOAT:
          dgram += osc_types.write_float(value)
        elif arg_type == self.ARG_TYPE_BLOB:
          dgram += osc_types.write_blob(value)
        elif arg_type == self.ARG_TYPE_TRUE or arg_type == self.ARG_TYPE_FALSE:
          continue
        else:
          raise BuildError('Incorrect parameter type found {}'.format(
              arg_type))
      return dgram
    except osc_types.BuildError as be:
      raise BuildError('Could not build the message: {}'.format(be))
Exemplo n.º 12
0
    def handleMsg(self, msg, type, name, uuid, *args, **kwargs):

        # Pop first frame as bytes, assumes single-frame message
        frameBytes = msg.pop()
        oscMsg = osc_message.OscMessage(frameBytes)

        if len(oscMsg.params) == 2:
            # Assume midi message
            channel = int(oscMsg.params[0])
            value = int(oscMsg.params[1])

            if channel == 1:
                # volume
                self.volume = ((1 - (value / 127.0)) * 60 - 0.5)
            elif channel == 11:
                # pitch
                self.pitch = (value / 127) * 2 - 1
        else:
            # Assume play cue
            name = oscMsg.address[1:]

            # alter pitch with pydub
            sound = AudioSegment.from_file(name + '.wav', format="wav")
            sound = sound - self.volume
            octaves = self.pitch
            newSampleRate = sound.frame_rate * (2.0**octaves)
            hipitch_sound = sound._spawn(
                sound.raw_data, overrides={'frame_rate': int(newSampleRate)})
            hipitch_sound = hipitch_sound.set_frame_rate(44100)

            # sound buffer with simpleaudio (non-blocking)
            simpleaudio.play_buffer(
                hipitch_sound.raw_data,
                num_channels=hipitch_sound.channels,
                bytes_per_sample=hipitch_sound.sample_width,
                sample_rate=hipitch_sound.frame_rate)

        return None
Exemplo n.º 13
0
 def cmd_rcvrtestfunc(self, sigstr):
     """..."""
     msg = osc_message.OscMessage(sigstr)
     print('In cmd_rcvrtestfunc, OSC address: {}'.format(msg.address))
     for idx, param in enumerate(msg.params):
         print('param[{0}]: {1}'.format(idx, param))
     if msg.address == '/cue':
         if msg.params[0] == "Next":
             print('OSC msg.params[0]: {}'.format(msg.params[0]))
             self.next_cue()
     elif msg.address == '/cue/#':
         print('cue # : {}'.format(msg.params[0]))
         #self.execute_cue(msg.params[0])
         The_Show.cues.currentcueindex = int(msg.params[0])
         self.tableView.setCurrentIndex(
             self.tablemodel.createIndex(The_Show.cues.currentcueindex, 0))
         #self.tableView.showRow(The_Show.cues.currentcueindex)
     elif msg.address == '/cue/uuid':
         print('cue uuid : {}'.format(msg.params[0]))
         #self.execute_cue_uuid(msg.params[0])
     elif msg.address == '/cue/quit':
         print('cue external quit')
         self.externalclose = True
         self.close()
Exemplo n.º 14
0
 def test_ignores_unknown_param(self):
     msg = osc_message.OscMessage(_DGRAM_UNKNOWN_PARAM_TYPE)
     self.assertEqual("/SYNC", msg.address)
     self.assertEqual(1, len(msg.params))
     self.assertTrue(type(msg.params[0]) == float)
     self.assertAlmostEqual(0.5, msg.params[0])
 def test_parse_long_params_list(self):
     msg = osc_message.OscMessage(_DGRAM_LONG_LIST)
     self.assertEqual("/SYNC", msg.address)
     self.assertEqual(1, len(msg.params))
     self.assertEqual(512, len(msg.params[0]))
Exemplo n.º 16
0
 def test_switch_goes_on(self):
     msg = osc_message.OscMessage(_DGRAM_SWITCH_GOES_ON)
     self.assertEqual("/SYNC", msg.address)
     self.assertEqual(1, len(msg.params))
     self.assertTrue(type(msg.params[0]) == float)
     self.assertAlmostEqual(0.5, msg.params[0])
Exemplo n.º 17
0
 def test_no_params(self):
     msg = osc_message.OscMessage(_DGRAM_NO_PARAMS)
     self.assertEqual("/SYNC", msg.address)
     self.assertEqual(0, len(msg.params))
Exemplo n.º 18
0
 def test_knob_rotates(self):
     msg = osc_message.OscMessage(_DGRAM_KNOB_ROTATES)
     self.assertEqual("/FB", msg.address)
     self.assertEqual(1, len(msg.params))
     self.assertTrue(type(msg.params[0]) == float)