88 lines
2.4 KiB
C#
88 lines
2.4 KiB
C#
namespace SIRTBroadcaster.Abstraction.Values
|
|
{
|
|
using Newtonsoft.Json;
|
|
|
|
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
|
|
[JsonConverter(typeof(RadioAddressConverter))]
|
|
public struct RadioAddress : IEnumerable<byte>
|
|
{
|
|
private readonly uint radioAddress;
|
|
private readonly byte[] addressBytes;
|
|
|
|
public RadioAddress(uint radioAddress)
|
|
{
|
|
this.radioAddress = radioAddress;
|
|
|
|
var bytes = BitConverter.GetBytes(radioAddress);
|
|
|
|
this.addressBytes = new byte[]
|
|
{
|
|
bytes[3],
|
|
bytes[2],
|
|
bytes[1],
|
|
bytes[0],
|
|
};
|
|
}
|
|
|
|
public RadioAddress(byte[] addressBytes)
|
|
{
|
|
this.addressBytes = addressBytes;
|
|
this.radioAddress = BitConverter.ToUInt32(addressBytes, 0);
|
|
}
|
|
|
|
public int Length => this.addressBytes.Length;
|
|
|
|
public IEnumerator<byte> GetEnumerator()
|
|
{
|
|
foreach (var @byte in this.addressBytes)
|
|
{
|
|
yield return @byte;
|
|
}
|
|
}
|
|
|
|
IEnumerator IEnumerable.GetEnumerator()
|
|
=> this.GetEnumerator();
|
|
|
|
public static implicit operator RadioAddress (uint radioAddress)
|
|
=> new RadioAddress(radioAddress);
|
|
|
|
public static implicit operator uint (RadioAddress radioAddress)
|
|
=> radioAddress.radioAddress;
|
|
|
|
public static implicit operator RadioAddress (byte[] addressBytes)
|
|
=> new RadioAddress(addressBytes);
|
|
|
|
public static implicit operator byte[] (RadioAddress radioAddress)
|
|
=> radioAddress.addressBytes;
|
|
}
|
|
|
|
public class RadioAddressConverter : JsonConverter
|
|
{
|
|
public override Boolean CanConvert(Type type)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
|
{
|
|
if (existingValue is RadioAddress radioAddress)
|
|
{
|
|
return radioAddress;
|
|
}
|
|
|
|
return default(uint);
|
|
}
|
|
|
|
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
|
{
|
|
if (value is RadioAddress radioAddress)
|
|
{
|
|
writer.WriteValue((uint)radioAddress);
|
|
}
|
|
}
|
|
}
|
|
}
|