using System; using System.Collections.Generic; namespace Passer.RoboidControl { /// <summary> /// A reference to a participant, possibly on a remote location /// </summary> public class RemoteParticipant { /// <summary> /// The internet address of the participant /// </summary> public string ipAddress = "0.0.0.0"; /// <summary> /// The UDP port on which the participant can be reached /// </summary> public int port = 0; /// <summary> /// The network ID of the participant /// </summary> public byte networkId; /// <summary> /// Default constructor /// </summary> public RemoteParticipant() {} /// <summary> /// Create a new remote participant /// </summary> /// <param name="ipAddress">The IP address of the participant</param> /// <param name="port">The UDP port of the participant</param> public RemoteParticipant(string ipAddress, int port) { this.ipAddress = ipAddress; this.port = port; } /// <summary> /// The things reported by this participant /// </summary> protected readonly List<Thing> things = new List<Thing>(); /// <summary> /// Get a thing with the given ids /// </summary> /// <param name="networkId">The network ID of the thing</param> /// <param name="thingId">The ID of the thing</param> /// <returns>The thing when it is found, null in other cases.</returns> public Thing Get(byte networkId, byte thingId) { Thing thing = things.Find(aThing => Thing.IsThing(aThing, networkId, thingId)); // if (thing == null) // Console.WriteLine($"Could not find thing {ipAddress}:{port}[{networkId}/{thingId}]"); return thing; } /// <summary> /// Add a new thing for this participant /// </summary> /// <param name="thing">The thing to add</param> /// <param name="invokeEvent">Invoke an notification event when the thing has been added</param> public void Add(Thing thing, bool invokeEvent = true) { // Console.WriteLine($"added thing [{thing.networkId}/{thing.id}]"); Thing foundThing = Get(thing.networkId, thing.id); if (foundThing == null) { things.Add(thing); if (invokeEvent) Thing.InvokeNewThing(thing); // Console.Write($"Add thing {ipAddress}:{port}[{networkId}/{thing.id}]"); } else { if (thing != foundThing) { // should be: find first non-existing id... thing.id = (byte)this.things.Count; things.Add(thing); // Console.Write($"Add thing, updated thing id to [{thing.networkId}/{thing.id}]"); } } } } }