using System.Collections.Generic; using System; namespace Unity.MLAgents.SideChannels { /// /// Side channel that is comprised of a collection of float variables. /// public class FloatPropertiesChannel : SideChannel { Dictionary m_FloatProperties = new Dictionary(); Dictionary> m_RegisteredActions = new Dictionary>(); const string k_FloatPropertiesDefaultId = "60ccf7d0-4f7e-11ea-b238-784f4387d1f7"; /// /// Initializes the side channel with the provided channel ID. /// /// ID for the side channel. public FloatPropertiesChannel(Guid channelId = default(Guid)) { if (channelId == default(Guid)) { ChannelId = new Guid(k_FloatPropertiesDefaultId); } else { ChannelId = channelId; } } /// protected override void OnMessageReceived(IncomingMessage msg) { var key = msg.ReadString(); var value = msg.ReadFloat32(); m_FloatProperties[key] = value; Action action; m_RegisteredActions.TryGetValue(key, out action); action?.Invoke(value); } /// /// Sets one of the float properties of the environment. This data will be sent to Python. /// /// The string identifier of the property. /// The float value of the property. public void Set(string key, float value) { m_FloatProperties[key] = value; using (var msgOut = new OutgoingMessage()) { msgOut.WriteString(key); msgOut.WriteFloat32(value); QueueMessageToSend(msgOut); } Action action; m_RegisteredActions.TryGetValue(key, out action); action?.Invoke(value); } /// /// Get an Environment property with a default value. If there is a value for this property, /// it will be returned, otherwise, the default value will be returned. /// /// The string identifier of the property. /// The default value of the property. /// public float GetWithDefault(string key, float defaultValue) { float valueOut; bool hasKey = m_FloatProperties.TryGetValue(key, out valueOut); return hasKey ? valueOut : defaultValue; } /// /// Registers an action to be performed everytime the property is changed. /// /// The string identifier of the property. /// The action that ill be performed. Takes a float as input. public void RegisterCallback(string key, Action action) { m_RegisteredActions[key] = action; } /// /// Returns a list of all the string identifiers of the properties currently present. /// /// The list of string identifiers public IList Keys() { return new List(m_FloatProperties.Keys); } } }