using System; using System.Net; using System.Net.Sockets; namespace RoboidControl { /// /// A site server is a participant which provides a shared simulated environment /// public class SiteServer : LocalParticipant { public SiteServer(int port = 7681) : this("0.0.0.0", port) { } /// /// Create a new site server /// /// public SiteServer(string ipAddress = "0.0.0.0", int port = 7681) : base() { this.name = "Site Server"; this.ipAddress = ipAddress; this.port = port; this.endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port); // for sending Console.Write($"Prepare receive on port {port}"); this.udpClient = new UdpClient(port); // for receiving this.udpClient.BeginReceive( new AsyncCallback(result => ReceiveUDP(result)), new Tuple(this.udpClient, new(IPAddress.Any, port))); Register(Thing.Type.TouchSensor); } /// /// Close the site /// public void Close() { this.udpClient?.Close(); } public override void Publish() { } protected override void Process(Participant remoteParticipant, ParticipantMsg msg) { if (msg.networkId == 0) { Console.WriteLine($"{this.name} received New Participant -> {remoteParticipant.networkId}"); this.Send(remoteParticipant, new NetworkIdMsg(remoteParticipant.networkId)); } } protected override void Process(Participant sender, NetworkIdMsg msg) { } protected override void Process(Participant sender, ThingMsg msg) { Console.WriteLine($"SiteServer: Process thing [{msg.networkId}/{msg.thingId}]"); Thing thing = sender.Get(msg.networkId, msg.thingId); if (thing == null) { Thing newThing = null; if (thingMsgProcessors.TryGetValue(msg.thingType, out Func msgProcessor)) { //Console.WriteLine("Found thing message processor"); if (msgProcessor != null) newThing = msgProcessor(sender, msg.networkId, msg.thingId); } if (newThing == null) { newThing = new Thing(sender, msg.networkId, msg.thingId, msg.thingType); // Console.WriteLine("Created generic new core thing"); } if (msg.parentId != 0) { Thing parentThing = Get(msg.networkId, msg.parentId); if (parentThing == null) Console.WriteLine($"Could not find parent [{msg.networkId}/{msg.parentId}]"); else newThing.parent = parentThing; } //Console.WriteLine("Adding to remote sender"); //sender.Add(newThing, false, true); } } } }