RoboidControl-csharp/ModelUrlMsg.cs
2025-01-01 09:58:15 +01:00

83 lines
3.1 KiB
C#

namespace Passer.Control.Core {
public class ModelUrlMsg : IMessage {
public const byte Id = 0x90; // (144) Model URL
public const byte length = 4;
public byte networkId;
public byte thingId;
public string? url = null;
public ModelUrlMsg(byte networkId, Thing thing) {
this.networkId = networkId;
this.thingId = thing.id;
this.url = thing.modelUrl;
}
public ModelUrlMsg(byte networkId, byte thingId, string url, float scale = 1) {
this.networkId = networkId;
this.thingId = thingId;
this.url = url;
}
public ModelUrlMsg(byte[] buffer) : base(buffer) { }
public override byte Serialize(ref byte[] buffer) {
byte ix = 0;
buffer[ix++] = ModelUrlMsg.Id;
buffer[ix++] = this.networkId;
buffer[ix++] = this.thingId; // Thing Id
buffer[ix++] = (byte)url.Length;
for (int urlIx = 0; urlIx < this.url.Length; urlIx++)
buffer[ix++] = (byte)url[urlIx];
return ix;
}
public override void Deserialize(byte[] buffer) {
byte ix = 0;
this.networkId = buffer[ix++];
this.thingId = buffer[ix++];
int strlen = buffer[ix++];
url = System.Text.Encoding.UTF8.GetString(buffer, (int)ix, strlen);
}
public static bool Send(Participant client, Thing thing) {
if (string.IsNullOrEmpty(thing.modelUrl))
return true; // nothing sent, but still a success!
ModelUrlMsg msg = new(thing.networkId, thing.id, thing.modelUrl);
return SendMsg(client, msg);
}
public static bool Send(Participant client, byte networkId, byte thingId, string modelUrl) {
if (string.IsNullOrEmpty(modelUrl))
return true; // nothing sent, but still a success!
ModelUrlMsg msg = new(networkId, thingId, modelUrl);
return SendMsg(client, msg);
}
public static async Task<bool> Receive(Stream dataStream, Participant client, byte packetSize) {
byte[] buffer = await Receive(dataStream, packetSize);
ModelUrlMsg msg = new(buffer);
client.messageQueue.Enqueue(msg);
return true;
}
public static bool SendTo(Participant participant, Thing thing) {
if (participant == null || thing == null || thing.modelUrl == null)
return false;
byte urlLength = (byte)thing.modelUrl.Length;
if (participant.buffer.Length < 3 + urlLength)
return false;
byte ix = 0;
participant.buffer[ix++] = ModelUrlMsg.Id;
participant.buffer[ix++] = participant.networkId;
participant.buffer[ix++] = thing.id; // Thing Id
participant.buffer[ix++] = urlLength;
for (int urlIx = 0; urlIx < urlLength; urlIx++)
participant.buffer[ix++] = (byte)thing.modelUrl[urlIx];
return participant.SendBuffer(ix);
}
}
}