Ejemplo n.º 1
0
        /// <summary>
        /// Add a osc message to the send queue
        /// </summary>
        /// <param name="message">message to send</param>
        public void Send(OscPacket message)
        {
            if (State != OscSocketState.Connected)
            {
                return;
            }

            queueEmpty.Reset();

            if (sendQueue.Count >= messageBufferSize)
            {
                return;
            }

            sendQueue.Enqueue(message);

            if (sendQueue.Count != 1)
            {
                return;
            }

            int size = message.Write(buffer);

            if (Statistics != null)
            {
                message.IncrementSendStatistics(Statistics);

                Statistics.BytesSent.Increment(size);
            }

            PacketSent?.Invoke(message);

            Socket.BeginSend(buffer, 0, size, SocketFlags, Send_Callback, message);
        }
Ejemplo n.º 2
0
        private void ListenLoop()
        {
            try
            {
                while (OscReceiver.State != OscSocketState.Closed)
                {
                    // if we are in a state to receive
                    if (OscReceiver.State != OscSocketState.Connected)
                    {
                        continue;
                    }

                    // get the next message
                    // this will block until one arrives or the socket is closed
                    OscPacket packet = OscReceiver.Receive();

                    PacketReceived?.Invoke(packet);

                    if (packet.Error == OscPacketError.None)
                    {
                        OscAddressManager.Invoke(packet);
                    }

                    PacketProcessed?.Invoke(packet);
                }
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Writes a single packet to the stream at the current position.
        /// </summary>
        /// <param name="packet">A osc packet</param>
        public void Write(OscPacket packet)
        {
            switch (Format)
            {
            case OscPacketFormat.Binary:
                byte[] bytes = packet.ToByteArray();

                // write the length
                Helper.Write(binaryWriter, bytes.Length);

                // write the packet
                binaryWriter.Write(bytes);
                break;

            case OscPacketFormat.Slip:
                byte[] preSlipBytes = packet.ToByteArray();
                byte[] slipBytes    = Slip.SlipPacketWriter.Write(preSlipBytes, 0, preSlipBytes.Length);

                // write the packet
                binaryWriter.Write(slipBytes);
                break;

            case OscPacketFormat.String:
                stringWriter.WriteLine(packet.ToString());
                break;

            default:
                throw new Exception($@"Invalid OSC stream format ""{Format}"".");
            }
        }
Ejemplo n.º 4
0
        private void ReceivedBytes(ref byte[] packetBytes, ref byte[] readBuffer)
        {
            // Fetch bytes from serial port
            //int bytesToRead = Math.Min(serialPort.BytesToRead, readBuffer.Length); // Don't use BytesToRead as it is not mono compatible
            int bytesToRead = readBuffer.Length;

            bytesToRead = serialPort.Read(readBuffer, 0, bytesToRead);

            Statistics?.BytesReceived.Increment(bytesToRead);

            int processed = 0;

            do
            {
                int packetLength;

                processed += reader.ProcessBytes(readBuffer, processed, bytesToRead - processed, ref packetBytes, out packetLength);

                if (packetLength <= 0)
                {
                    continue;
                }

                OscPacket oscPacket = OscPacket.Read(packetBytes, packetLength);

                if (Statistics != null && oscPacket.Error != OscPacketError.None)
                {
                    Statistics.ReceiveErrors.Increment(1);
                }

                PacketRecived?.Invoke(oscPacket);
            }while (processed < bytesToRead);
        }
Ejemplo n.º 5
0
        public void Send(OscPacket packet)
        {
            if (Statistics != null)
            {
                packet.IncrementSendStatistics(Statistics);
            }

            writer.Write(packet);
            file.Flush();
        }
Ejemplo n.º 6
0
        public UnknownAddressEventArgs(object sender, string address, OscPacket packet)
        {
            Retry = false;

            Sender = sender;

            Address = address;

            Packet = packet;
        }
Ejemplo n.º 7
0
        private void Receive_Callback(IAsyncResult ar)
        {
            try
            {
                // create an empty origin
                EndPoint origin = UseIPv6 ? Helper.EmptyEndPointIPv6 : Helper.EmptyEndPoint;

                int count = Socket.EndReceiveFrom(ar, ref origin);

                Statistics?.BytesReceived.Increment(count);

                OscPacket message = OscPacket.Read(buffer, count, (IPEndPoint)origin);

                if (Statistics != null && message.Error != OscPacketError.None)
                {
                    Statistics.ReceiveErrors.Increment(1);
                }

                if (receiveQueue.Count < messageBufferSize)
                {
                    receiveQueue.Enqueue(message);

                    messageReceived.Set();
                }

                //lock (syncLock)
                //{
                //    if (this.count < receiveQueue.Length)
                //    {
                //        receiveQueue[writeIndex] = message;

                //        writeIndex = NextWriteIndex;

                //        this.count++;

                //        // if this was the first message then signal
                //        if (this.count == 1)
                //        {
                //            messageReceived.Set();
                //        }
                //    }
                //}
            }
            catch
            {
            }

            if (State == OscSocketState.Connected)
            {
                // create an empty origin
                EndPoint origin = UseIPv6 ? Helper.EmptyEndPointIPv6 : Helper.EmptyEndPoint;

                Socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags, ref origin, Receive_Callback, null);
            }
        }
Ejemplo n.º 8
0
        public static bool TryParse(string str, IFormatProvider provider, out OscPacket packet)
        {
            try
            {
                packet = Parse(str, provider);

                return(true);
            }
            catch
            {
                packet = default(OscPacket);

                return(false);
            }
        }
Ejemplo n.º 9
0
        private bool OnUnknownAddress(string address, OscPacket packet)
        {
            if (UnknownAddress != null)
            {
                UnknownAddressEventArgs arg = new UnknownAddressEventArgs(this, address, packet);

                UnknownAddress(this, arg);

                return(arg.Retry);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Invoke a osc packet
        /// </summary>
        /// <param name="packet">the packet</param>
        /// <returns>true if any thing was invoked</returns>
        public bool Invoke(OscPacket packet)
        {
            Statistics?.PacketsReceived.Increment(1);

            switch (packet)
            {
            case OscMessage _:
                return(Invoke((OscMessage)packet));

            case OscBundle _:
                return(Invoke((OscBundle)packet));
            }

            throw new Exception($"Unknown osc packet type '{packet}'");
        }
Ejemplo n.º 11
0
        public OscPacket Read()
        {
            long position = reader.BaseStream.Position;

            OscPacket packet = reader.Read();

            long newPosition = reader.BaseStream.Position;

            Statistics?.BytesReceived.Increment((int)(newPosition - position));

            if (Statistics != null && packet.Error != OscPacketError.None)
            {
                Statistics.ReceiveErrors.Increment(1);
            }

            PacketRecived?.Invoke(packet);

            return(packet);
        }
Ejemplo n.º 12
0
        public void Send(OscPacket packet)
        {
            if (serialPort == null)
            {
                throw new Exception("Serial port is not connected");
            }

            byte[] packetBytes  = packet.ToByteArray();
            byte[] slippedBytes = SlipPacketWriter.Write(packetBytes, 0, packetBytes.Length);

            if (Statistics != null)
            {
                packet.IncrementSendStatistics(Statistics);

                Statistics.BytesSent.Increment(packetBytes.Length);
            }

            serialPort.Write(slippedBytes, 0, slippedBytes.Length);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Receive a osc message, this method is blocking and will only return once a message is recived
        /// </summary>
        /// <returns>an osc message</returns>
        public OscPacket Receive()
        {
            try
            {
                if (State == OscSocketState.Connected)
                {
                    // if we are not receiving then start
                    if (isReceiving == false && State == OscSocketState.Connected)
                    {
                        BeginReceiving();
                    }

                    OscPacket message = null;

                    while (State == OscSocketState.Connected && receiveQueue.TryDequeue(out message) == false)
                    {
                        // wait for a new message
                        messageReceived.WaitOne();
                        //messageReceived.Reset();
                    }

                    if (message != null)
                    {
                        return(message);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new OscSocketException(this, "An unexpected error occured while waiting for a message", ex);
            }

            if (State == OscSocketState.Connected)
            {
                throw new OscSocketException(this, "An unexpected error occured while waiting for a message");
            }

            throw new OscSocketStateException(this, OscSocketState.Closed, "The receiver socket is not connected");
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Try to receive a osc message, this method is non-blocking and will return imediatly with a message or null
        /// </summary>
        /// <param name="message">an osc message if one is ready else null if there are none</param>
        /// <returns>true if a message was ready</returns>
        public bool TryReceive(out OscPacket message)
        {
            message = null;

            if (State != OscSocketState.Connected)
            {
                return(false);
            }

            if (receiveQueue.TryDequeue(out message) == false)
            {
                // wait for a new message
                //messageReceived.WaitOne();
                //messageReceived.Reset();
            }

            // if we are not receiving then start
            if (isReceiving == false && State == OscSocketState.Connected)
            {
                BeginReceiving();
            }

            return(message != null);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Read a single packet from the stream at the current position
        /// </summary>
        /// <returns>An osc packet</returns>
        public OscPacket Read()
        {
            switch (Format)
            {
            case OscPacketFormat.Binary:
                int length = Helper.ReadInt32(binaryReader);

                byte[] bytes = new byte[length];

                binaryReader.Read(bytes, 0, length);

                return(OscPacket.Read(bytes, length));

            case OscPacketFormat.Slip:
                byte[] packetBytes  = new byte[slipReader.BufferSize];
                int    packetLength = 0;

                do
                {
                    if (slipByteCount - slipByteIndex == 0)
                    {
                        slipByteIndex = 0;

                        slipByteCount = binaryReader.Read(slipByteCache, 0, slipByteCache.Length);
                    }

                    slipByteIndex += slipReader.ProcessBytes(slipByteCache, slipByteIndex, slipByteCount - slipByteIndex, ref packetBytes, out packetLength);
                }while (packetLength <= 0 && EndOfStream == false);

                return(packetLength > 0 ? OscPacket.Read(packetBytes, packetLength) : OscMessage.ParseError);

            case OscPacketFormat.String:
                string    line = stringReader.ReadLine();
                OscPacket packet;

                if (OscPacket.TryParse(line, out packet) == false)
                {
                    StringBuilder sb = new StringBuilder();

                    sb.AppendLine(line);

                    while (EndOfStream == false)
                    {
                        sb.Append(stringReader.ReadLine());

                        if (OscPacket.TryParse(sb.ToString(), out packet) == true)
                        {
                            return(packet);
                        }

                        sb.AppendLine();
                    }

                    return(OscMessage.ParseError);
                }

                return(packet);

            default:
                throw new Exception($@"Invalid OSC stream format ""{Format}"".");
            }
        }