RoboidControl-csharp/SiteServer.cs
2025-02-25 15:46:58 +01:00

81 lines
3.0 KiB
C#

using System;
using System.Net;
using System.Net.Sockets;
namespace RoboidControl {
/// <summary>
/// A site server is a participant which provides a shared simulated environment
/// </summary>
public class SiteServer : Participant {
public SiteServer(int port = 7681) : this("0.0.0.0", port) { }
/// <summary>
/// Create a new site server
/// </summary>
/// <param name="port"></param>
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<UdpClient, IPEndPoint>(this.udpClient, new(IPAddress.Any, port)));
Register<TouchSensor>(Thing.Type.TouchSensor);
}
/// <summary>
/// Close the site
/// </summary>
public void Close() {
this.udpClient?.Close();
}
public override void Publish() {
}
protected override void Process(RemoteParticipant sender, ParticipantMsg msg) {
if (msg.networkId == 0) {
Console.WriteLine($"{this.name} received New Client -> {sender.networkId}");
this.Send(sender, new NetworkIdMsg(sender.networkId));
}
}
protected override void Process(RemoteParticipant sender, NetworkIdMsg msg) { }
protected override void Process(RemoteParticipant 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<RemoteParticipant, byte, byte, Thing> value)) {
// Console.WriteLine("Found thing message processor");
if (value != null)
newThing = value(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");
else
newThing.parent = parentThing;
}
sender.Add(newThing);
}
}
}
}