81 lines
2.9 KiB
C#
81 lines
2.9 KiB
C#
namespace Passer.Control.Core {
|
|
|
|
public class NameMsg : IMessage {
|
|
public const byte Id = 0x91; // 145
|
|
public const byte length = 4;
|
|
public byte networkId;
|
|
public byte thingId;
|
|
public byte len;
|
|
public string? name = null;
|
|
|
|
public NameMsg(byte networkId, Thing thing) {
|
|
this.networkId = networkId;
|
|
this.thingId = thing.id;
|
|
this.name = thing.name;
|
|
}
|
|
public NameMsg(byte networkId, byte thingId, string name) {
|
|
this.networkId = networkId;
|
|
this.thingId = thingId;
|
|
this.name = name;
|
|
}
|
|
public NameMsg(byte[] buffer) : base(buffer) { }
|
|
|
|
public override byte Serialize(ref byte[] buffer) {
|
|
byte ix = 0;
|
|
buffer[ix++] = NameMsg.Id;
|
|
buffer[ix++] = this.networkId;
|
|
buffer[ix++] = this.thingId;
|
|
buffer[ix++] = (byte)this.name.Length;
|
|
for (int nameIx = 0; nameIx < this.name.Length; nameIx++)
|
|
buffer[ix++] = (byte)this.name[nameIx];
|
|
return ix;
|
|
}
|
|
public override void Deserialize(byte[] buffer) {
|
|
byte ix = 0;
|
|
this.networkId = buffer[ix++];
|
|
this.thingId = buffer[ix++];
|
|
int strlen = buffer[ix++];
|
|
this.name = System.Text.Encoding.UTF8.GetString(buffer, (int)ix, strlen);
|
|
}
|
|
|
|
public static bool Send(Participant client, Thing thing) {
|
|
if (string.IsNullOrEmpty(thing.name))
|
|
return true; // nothing sent, but still a success!
|
|
|
|
NameMsg msg = new(thing.networkId, thing.id, thing.name);
|
|
return SendMsg(client, msg);
|
|
}
|
|
//public static bool Send(Client client, byte networkId, byte thingId, string name)
|
|
//{
|
|
// NameMsg msg = new(networkId, thingId, name);
|
|
// return SendMsg(client, msg);
|
|
//}
|
|
public static async Task<bool> Receive(Stream dataStream, Participant client, byte packetSize) {
|
|
byte[] buffer = await Receive(dataStream, packetSize);
|
|
NameMsg msg = new(buffer);
|
|
|
|
client.messageQueue.Enqueue(msg);
|
|
return true;
|
|
}
|
|
|
|
public static bool SendTo(Participant participant, Thing thing) {
|
|
if (participant == null || thing == null || thing.name == null)
|
|
return false;
|
|
|
|
byte nameLength = (byte)thing.name.Length;
|
|
if (participant.buffer.Length < 3 + nameLength)
|
|
return false;
|
|
|
|
byte ix = 0;
|
|
participant.buffer[ix++] = NameMsg.Id;
|
|
participant.buffer[ix++] = participant.networkId;
|
|
participant.buffer[ix++] = thing.id;
|
|
participant.buffer[ix++] = nameLength;
|
|
for (int nameIx = 0; nameIx < nameLength; nameIx++)
|
|
participant.buffer[ix++] = (byte)thing.name[nameIx];
|
|
|
|
return participant.SendBuffer(ix);
|
|
}
|
|
}
|
|
|
|
} |