RoboidControl-csharp/src/SiteServer.cs
2025-03-19 17:35:21 +01:00

81 lines
3.1 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 : LocalParticipant {
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(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<Participant, byte, byte, Thing> 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);
}
}
}
}