void UnpackRecursivelyAndDispatch(OscPacket packet) { if (packet is OscBundle) { OscBundle bundle = packet as OscBundle; foreach (OscPacket subPacket in bundle.packets) { if (_addTimeTagsToBundledMessages && subPacket is OscMessage) { OscMessage message = subPacket as OscMessage; message.Add(bundle.timeTag); } UnpackRecursivelyAndDispatch(subPacket); } OscPool.Recycle(bundle); } else { OscMessage message = packet as OscMessage; if (_filterDuplicates) { if (_uniqueAddresses.Contains(message.address)) { OscPool.Recycle(message); return; } _uniqueAddresses.Add(message.address); } Dispatch(packet as OscMessage); _messageCount++; // Influenced by _filterDuplicates. } }
public void Send(string address, params object[] args) { OscMessage message = OscPool.GetMessage(address); message.Add(args); SendPooled(message); }
void OnReceived2(OscMessage message) { // Log. Debug.Log("Received\n" + message); // Always recycle incoming messages when used. OscPool.Recycle(message); }
public static bool TryReadFrom(byte[] data, ref int index, int byteCount, out OscBundle bundle) { // Check header size (prefix + timetag). if (data.Length - index < OscConst.bundleHeaderSize) { Debug.LogWarning("[OscParser] OscBundle with invalid header was ignored." + Environment.NewLine); // TODO make warnings optional bundle = null; return(false); } // Check prefix. if (!ReadAndValidatePrefix(data, ref index)) { Debug.LogWarning("[OscParser] OscBundle with invalid header was ignored." + Environment.NewLine); // TODO make warnings optional bundle = null; return(false); } // Try get recycled bundle from the pool, otherwise create new. bundle = OscPool.GetBundle(); // Get timetag osc ntp. EightByteOscData timeTagDataValue; EightByteOscData.TryReadFrom(data, ref index, out timeTagDataValue); bundle.timeTag = timeTagDataValue.timeTagValue; // Fill Bundle. while (index < byteCount) { FourByteOscData packetSizeDataValue; if (!FourByteOscData.TryReadFrom(data, ref index, out packetSizeDataValue)) { break; } if (index + packetSizeDataValue.intValue > data.Length) { Debug.LogWarning("[OscParser] Incomplete OscBundle was ignored.\nPerhaps your UDP buffer size is too small.\n"); // TODO make warnings optional bundle = null; return(false); } OscPacket subPacket; if (TryReadFrom(data, ref index, byteCount, out subPacket)) { bundle.Add(subPacket); } else { Debug.Log("Failed to read packet."); // TODO make warnings optional } } // Done. return(true); }
void OnMessageReceived(OscMessage message) { // Use TryGetFromBlob to read a list of floats from a byte blob. if (message.TryGetBlob(0, ref _receivedFloats)) { Debug.Log("Receiving: " + ListToString(_receivedFloats) + "\n"); } // Always recycle received messages when used. OscPool.Recycle(message); }
void OnAnyMessage(OscMessage message) { if (_messageStringQueue.Count >= messageBufferCapacity) { _messageStringQueue.Dequeue(); } _messageStringQueue.Enqueue(message.ToString()); // Always recycle received messages, also when received from OscOut. OscPool.Recycle(message); }
/// <summary> /// Send an OscMessage or OscBundle. Data is serialized and no reference is stored, so you can safely /// change values and send packet immediately again. /// Returns success status. /// </summary> public bool Send( OscPacket packet ) { if( !isOpen ) return false; // On any message. if( _onAnyMessage != null ) InvokeAnyMessageEventRecursively( packet ); // Individual messages are always send in bundles at end of frame. if( packet is OscMessage ){ _endOfFrameBuffer.Add( packet as OscMessage ); return true; // Assume success. } // Split bundle case. if( packet.Size() > _udpBufferSize ){ ExtractMessages( packet, _tempMessageQueue ); int bundleByteCount = OscConst.bundleHeaderSize; OscBundle splitBundle = OscPool.GetBundle(); while( _tempMessageQueue.Count > 0 ) { OscMessage message = _tempMessageQueue.Dequeue(); // Check if message is too big. int messageSize = message.Size() + FourByteOscData.byteCount; // Bundle stores size of each message in a 4 byte integer. if( messageSize > _udpBufferSize ){ StringBuilder sb = OscDebug.BuildText( this ); sb.Append( "Failed to send message. Message size at " ); sb.Append( messageSize ); sb.Append( " bytes exceeds udp buffer size at " ); sb.Append( _udpBufferSize ); sb.Append( " bytes. Try increasing the buffer size.'\n" ); Debug.LogWarning( sb.ToString() ); return false; } // If bundle is full, send it and prepare for new bundle. if( bundleByteCount + messageSize > _udpBufferSize ) { if( !Send( splitBundle ) ) return false; bundleByteCount = OscConst.bundleHeaderSize; splitBundle.Clear(); } splitBundle.packets.Add( message ); bundleByteCount += messageSize; } if( splitBundle.packets.Count > 0 && !Send( splitBundle ) ) return false; OscPool.Recycle( splitBundle ); return true; } // Try to pack the message. int index = 0; if( !packet.TryWriteTo( _cache, ref index ) ) return false; //Debug.Log( $"Sending byte count {index}" ); // Send data! return TrySendCache( index ); }
void OnReceiveVertex(OscMessage message) { // meshfilter.mesh.Clear(); // mesh.vertices. var vertices = new List <Vector3>(); // indices = new List<int>(); if (message.TryGetBlob(0, ref _receivedFloats)) { // Debug.Log( "vertex: " + ListToString( _receivedFloats ) + "\n" ); var count = 0; for (int i = 0; i < _receivedFloats.Count; i += 3) { var x = _receivedFloats[i]; var y = _receivedFloats[i + 1]; var z = _receivedFloats[i + 2]; vertices.Add(new Vector3(x, y, z)); baseVertices[count] = new Vector3(x, y, z); // indices.Add(count); count++; } } Debug.Log(vertices.Count); Debug.Log(baseVertices.Count); // if(mesh.vertices.Length != vertices.Count) return; // mesh.Clear(); // Debug.Log(indices.Count); // // if (indices.Count < 3) // { // int count = 0; // while (indices.Count < 3) // { // indices.Add(count); // Debug.Log(count); // count++; // } // } mesh.SetVertices(baseVertices); // mesh.vertices = baseVertices.ToArray(); mesh.SetIndices(indices.ToArray(), MeshTopology.Triangles, 0); mesh.RecalculateNormals(); meshfilter.sharedMesh = mesh; OscPool.Recycle(message); }
void SendPooled(OscMessage message) { if (isOpen) { Send(message); } if (_onAnyMessage == null) { OscPool.Recycle(message); } }
void SendPooled(OscMessage message) { if (isOpen) { Send(message); } if (_onAnyMessageListenerCount == 0) { OscPool.Recycle(message); } }
void OnMessageReceived(OscMessage message) { // Use TryGetFromBlob to read a Vector2 value from a byte blob. Vector2 value; if (message.TryGetBlob(0, out value)) { Debug.Log("Receiving: " + value + "\n"); } // Always recycle received messages when used. OscPool.Recycle(message); }
void OnMessageReceived(OscMessage message) { // Use TryGetFromBlob to read a Vector2 value from a byte blob. string receviedText; if (message.TryGetBlob(0, System.Text.Encoding.UTF8, out receviedText)) { Debug.Log("Receiving: " + receviedText + "\n"); } // Always recycle received messages when used. OscPool.Recycle(message); }
void Dispatch(OscMessage message) { bool anyMessageActivated = _onAnyMessageListenerCount > 0; bool messageExposed = anyMessageActivated; // Regular mappings. Dictionary <string, OscMapping> mappingLookup; if (_regularMappingLookup.TryGetValue(message.GetAddressHash(), out mappingLookup)) { OscMapping mapping; if (mappingLookup.TryGetValue(message.address, out mapping)) { InvokeMapping(mapping, message); if (!messageExposed) { messageExposed = mapping.type == OscMessageType.OscMessage; } } } // Special pattern mappings. foreach (OscMapping specialMapping in _specialPatternMappings) { if (specialMapping.IsMatching(message.address)) { InvokeMapping(specialMapping, message); if (!messageExposed) { messageExposed = specialMapping.type == OscMessageType.OscMessage; } } } // Any message handler. if (anyMessageActivated) { _onAnyMessage.Invoke(message); } #if UNITY_EDITOR // Editor inspector. _inspectorMessageEvent.Invoke(message); #endif // Recycle when possible. if (!anyMessageActivated && !messageExposed) { OscPool.Recycle(message); } }
void OnMessageReceived(OscMessage incomingMessage) { // Try to get the string from the message at arg index 0. if (incomingMessage.TryGet(0, ref _incomingText)) { // We have now received a string that will only be // recreated (generate garbage) if it changes. // However, this Debug.Log call will generate garbage. Lots of it ;) Debug.Log(_incomingText); } // OPTIMISATION #4 // Always recycle messages when you handle them yourself. OscPool.Recycle(incomingMessage); }
void Dispatch(OscMessage message) { bool anyMessageActivated = _onAnyMessage != null; bool messageExposed = anyMessageActivated; string address = message.address; // Regular mappings. if (_mappedAddresses.Contains(address)) { OscMapping mapping; if (_regularMappings.TryGetValue(address, out mapping)) { InvokeMapping(mapping, message); if (!messageExposed) { messageExposed = mapping.type == OscMessageType.OscMessage; } } } // Special pattern mappings. foreach (OscMapping specialMapping in _specialPatternMappings) { if (specialMapping.IsMatching(message.address)) { InvokeMapping(specialMapping, message); if (!messageExposed) { messageExposed = specialMapping.type == OscMessageType.OscMessage; } } } // Any message handler. if (anyMessageActivated) { _onAnyMessage.Invoke(message); } // Recycle when possible. if (!anyMessageActivated && !messageExposed) { OscPool.Recycle(message); } }
void OnTest2(OscMessage message) { // Get arguments from index 0, 1 and 2 safely. int frameCount; float time; float random; if ( message.TryGet(0, out frameCount) && message.TryGet(1, out time) && message.TryGet(2, out random) ) { Debug.Log("Received test2\n" + frameCount + " " + time + " " + random + "\n"); } // If you don't know what type of arguments to expect, then you // can check the type of each argument and get the ones you need. for (int i = 0; i < message.Count(); i++) { OscArgType argType; if (!message.TryGetArgType(i, out argType)) { continue; } switch (argType) { case OscArgType.Float: float floatValue; message.TryGet(i, out floatValue); // Do something with floatValue here... break; case OscArgType.Int: int intValue; message.TryGet(i, out intValue); // Do something with intValue here... break; } } // Always recycle incoming messages when used. OscPool.Recycle(message); }
void ParseRecievedNotice(OscMessage message) { string type = ""; if (message.TryGet(0, ref type)) { byte[] data = new byte[0]; switch (type) { case "text": if (message.TryGet(1, ref data)) { int duration = 10; message.TryGet(2, out duration); ToryUX.ToryNotification.Instance.Show(System.Text.Encoding.UTF8.GetString(data), duration); } break; case "backgroundColor": if (message.TryGet(1, ref data)) { if (data.Length >= 4) { ToryUX.ToryNotification.Instance.SetBackgroundColor(new Color32(data[0], data[1], data[2], data[3])); } } break; case "textColor": if (message.TryGet(1, ref data)) { if (data.Length >= 4) { ToryUX.ToryNotification.Instance.SetTextColor(new Color32(data[0], data[1], data[2], data[3])); } } break; default: break; } } OscPool.Recycle(message); }
/// <summary> /// Send an OscMessage with no arguments. /// </summary> public void Send( string address ){ SendPooled( OscPool.GetMessage( address ) ); }
/// <summary> /// Send an OscMessage with a single argument. /// </summary> public void Send( string address, OscImpulse value ){ SendPooled( OscPool.GetMessage( address ).Add( value ) ); }
/// <summary> /// Send an OscMessage with a single argument. /// </summary> public void Send( string address, byte[] value ){ SendPooled( OscPool.GetMessage( address ).Add( value ) ); }
// TODO void ParseRecievedMessage(OscMessage message) { OscPool.Recycle(message); }
/// <summary> /// Send an OscMessage or OscBundle. Data is serialized and no reference is stored, so you can safely /// change values and send packet immediately again. /// Returns success status. /// </summary> public bool Send(OscPacket packet) { if (!isOpen) { return(false); } int index = 0; // On any message. if (_onAnyMessage != null) { InvokeAnyMessageEventRecursively(packet); } // Adapt buffer size. if (_sendBuffer == null || _sendBuffer.Length != _udpBufferSize) { _sendBuffer = new byte[_udpBufferSize]; } // Handle user messages. if (packet is OscMessage) { if (_bundleMessagesAutomatically) { // Collect to be bundled and send by end of the Unity frame. _autoBundleMessageBuffer.Add(packet as OscMessage); return(true); // Assume success. } else { // Add to cache and send immediately. OscMessage message = packet as OscMessage; message.TryWriteTo(_sendBuffer, ref index); bool success = TrySendBuffer(index); if (success) { _messageCountThisFrame++; } return(success); } } // Handle user bundles. Bundles provided by the user are send immediately. If too big, they are split into more bundles. OscBundle bundle = packet as OscBundle; if (bundle.Size() > _udpBufferSize) { ExtractMessages(packet, _userBundleTempMessages); int bundleByteCount = OscConst.bundleHeaderSize; OscBundle splitBundle = OscPool.GetBundle(); while (_userBundleTempMessages.Count > 0) { OscMessage message = _userBundleTempMessages.Dequeue(); // Check if message is too big. int messageSize = message.Size() + FourByteOscData.byteCount; // Bundle stores size of each message in a 4 byte integer. if (messageSize > _udpBufferSize) { if (OscGlobals.logWarnings) { StringBuilder sb = OscDebug.BuildText(this); sb.Append("Failed to send message. Message size at "); sb.Append(messageSize); sb.Append(" bytes exceeds udp buffer size at "); sb.Append(_udpBufferSize); sb.Append(" bytes. Try increasing the buffer size.'\n"); Debug.LogWarning(sb.ToString()); } return(false); } // If bundle is full, send it and prepare for new bundle. if (bundleByteCount + messageSize > _udpBufferSize) { if (!Send(splitBundle)) { return(false); } bundleByteCount = OscConst.bundleHeaderSize; splitBundle.Clear(); } splitBundle.packets.Add(message); bundleByteCount += messageSize; } if (splitBundle.packets.Count > 0 && !Send(splitBundle)) { return(false); } OscPool.Recycle(splitBundle); return(true); } // Try to pack the message. if (!bundle.TryWriteTo(_sendBuffer, ref index)) { return(false); } _messageCountThisFrame += bundle.packets.Count; // Send data! return(TrySendBuffer(index)); }
// Undocumented on purpose. public static bool TryReadFrom(byte[] data, ref int index, int size, ref OscMessage message) { int beginIndex = index; // If we are not provided with a message, then read the lossy hash and try reuse from the pool. if (message == null) { int hash = OscStringHash.Pack(data, index); message = OscPool.GetMessage(hash); } else { if (message._argInfo.Count > 0) { message.Clear(); // Ensure that arguments are cleared. } } // Address. string address = message._address; if (!StringOscData.TryReadFrom(data, ref index, ref address)) { Debug.Log(OscDebug.FailedReadingBytesWarning(message)); return(false); } message._address = address; // Tag prefix. if (data[index] != OscConst.tagPrefixByte) { StringBuilder sb = OscDebug.BuildText(message); sb.Append("Read failed. Tag prefix missing.\n"); Debug.LogWarning(sb.ToString()); return(false); } index++; // Argument tags. for (int i = index; i < data.Length && data[i] != 0; i++) { message._argInfo.Add(new OscArgInfo(data[i], 0)); } index += message._argInfo.Count; // Followed by at least one trailing zero, multiple of four bytes. index += 4 - (index % 4); //Debug.Log( "READ: Args data start index: " + index ); // Argument data info. int argDataByteCount = 0; for (int i = 0; i < message._argInfo.Count; i++) { byte tagByte = message._argInfo[i].tagByte; int argByteCount = 0; switch (tagByte) { case OscConst.tagNullByte: case OscConst.tagImpulseByte: case OscConst.tagTrueByte: case OscConst.tagFalseByte: break; case OscConst.tagFloatByte: case OscConst.tagIntByte: case OscConst.tagCharByte: case OscConst.tagColorByte: case OscConst.tagMidiByte: argByteCount = 4; break; case OscConst.tagDoubleByte: case OscConst.tagLongByte: case OscConst.tagTimetagByte: argByteCount = 8; break; case OscConst.tagStringByte: case OscConst.tagSymbolByte: argByteCount = StringOscData.EvaluateByteCount(data, index + argDataByteCount); break; case OscConst.tagBlobByte: BlobOscData.TryEvaluateByteCount(data, index + argDataByteCount, out argByteCount); break; default: StringBuilder sb = OscDebug.BuildText(message); sb.Append("Read failed. Tag '"); sb.Append((char)tagByte); sb.Append("' is not supported\n"); Debug.LogWarning(sb.ToString()); return(false); } message._argInfo[i] = new OscArgInfo(tagByte, argByteCount); //Debug.Log( "i; " + i + ", info: " + message._argInfo[i] ); argDataByteCount += argByteCount; } // AdaptiveSet data list. if (message._argData.Capacity < argDataByteCount) { message._argData.Capacity = argDataByteCount; } // Read data. for (int i = 0; i < argDataByteCount; i++) { message._argData.Add(data[index++]); } // Cache byte count. message._cachedSize = index - beginIndex; message._dirtySize = false; return(true); }
public static bool TryReadFrom(byte[] data, ref int index, int byteCount, out OscBundle bundle) { //Debug.Log( "OscBundle.TryReadFrom. index: " + index + ", expected byteCount: " + byteCount ); // Check header size (prefix + timetag). if (data.Length - index < OscConst.bundleHeaderSize) { if (OscGlobals.logWarnings) { Debug.LogWarning(logPrepend + "OscBundle with invalid header was ignored." + Environment.NewLine); } bundle = null; return(false); } // Check prefix. if (!ReadAndValidatePrefix(data, ref index)) { if (OscGlobals.logWarnings) { Debug.LogWarning(logPrepend + "OscBundle with invalid header was ignored." + Environment.NewLine); } bundle = null; return(false); } // Try get recycled bundle from the pool, otherwise create new. bundle = OscPool.GetBundle(); // Get (optional) timetag osc ntp. EightByteOscData timeTagDataValue; if (EightByteOscData.TryReadFrom(data, ref index, out timeTagDataValue)) { bundle.timeTag = timeTagDataValue.timeTagValue; //Debug.Log( "Time tag: " + bundle.timeTag ); } // Extract packets from buffer data. while (index < byteCount) { //Debug.Log( "Read index: " + index + " out of " + byteCount ); // Read packet size. FourByteOscData packetSizeDataValue; if (!FourByteOscData.TryReadFrom(data, ref index, out packetSizeDataValue) || packetSizeDataValue.intValue == 0) { //Debug.LogError( "No message size provided!" ); break; } //Debug.Log( "packetSizeData: " + packetSizeDataValue.intValue ); int endDataIndex = index + packetSizeDataValue.intValue; if (endDataIndex > data.Length) { if (OscGlobals.logWarnings) { //Debug.LogError( "packetSizeDataValue.intValue: " + packetSizeDataValue.intValue ); Debug.LogWarning(string.Format( "{0}Failed to read OscBundle at index {1} because a OscPacket is too large to fit in buffer (byte size {2}.\n" + "Your buffer may be too small to read the entire bundle. Try increasing the buffer size in OscIn.", logPrepend, index, packetSizeDataValue.intValue )); } bundle = null; return(false); } //if( index % 4 != 0 ) Debug.LogError( "NOT MULTIPLE OF 4" ); OscPacket subPacket; //Debug.Log( ( (char) data[ index ] ) + " " + data[ index ] ); if (TryReadFrom(data, ref index, endDataIndex, out subPacket)) { //Debug.Log( "Sub packet read: " + index + " == " + endDataIndex ); bundle.Add(subPacket); } else { if (OscGlobals.logWarnings) { Debug.LogWarning(logPrepend + "Failed to read packet.\nIndex: " + index + ", Packet size: " + packetSizeDataValue.intValue + ", Byte count: " + byteCount + ", Buffer size: " + data.Length); } return(false); } } // Done. return(true); }
// TODO void ParseReceivedCommand(OscMessage message) { OscPool.Recycle(message); }