|
| 1 | +using HomeKitDotNet.JSON; |
| 2 | +using System.Buffers.Text; |
| 3 | +using System.Text.Json; |
| 4 | + |
| 5 | +namespace HomeKitDotNet.Models |
| 6 | +{ |
| 7 | + public class BinaryCharacteristic : CharacteristicBase |
| 8 | + { |
| 9 | + public delegate Task AsyncEventHandler(Service service, BinaryCharacteristic characteristic, byte[] newValue); |
| 10 | + public event AsyncEventHandler? Updated; |
| 11 | + protected BinaryCharacteristic(Service service, CharacteristicJSON json) : base(service, json) |
| 12 | + { |
| 13 | + LastValue = MapValue(json.Value); |
| 14 | + } |
| 15 | + |
| 16 | + protected async Task<bool> Write(byte[] value) |
| 17 | + { |
| 18 | + if (!CanWrite) |
| 19 | + throw new InvalidOperationException("Writing is prohibited"); |
| 20 | + CharacteristicValueJSON write = new CharacteristicValueJSON(service.Accessory.ID, InstanceID); |
| 21 | + write.Value = JsonSerializer.SerializeToElement(Convert.ToBase64String(value)); |
| 22 | + Dictionary<string, CharacteristicValueJSON[]> dict = new Dictionary<string, CharacteristicValueJSON[]>(); |
| 23 | + dict.Add("characteristics", [write]); |
| 24 | + return (await service.Accessory.EndPoint.Connection.Put("/characteristics", JsonSerializer.SerializeToUtf8Bytes(dict))).StatusCode == System.Net.HttpStatusCode.NoContent; |
| 25 | + } |
| 26 | + |
| 27 | + protected async Task<byte[]> Read() |
| 28 | + { |
| 29 | + if (!CanRead) |
| 30 | + throw new InvalidOperationException("Reading is prohibited"); |
| 31 | + HttpResponseMessage msg = await service.Accessory.EndPoint.Connection.Get($"/characteristics?id={service.Accessory.ID}.{InstanceID}"); |
| 32 | + if (!msg.IsSuccessStatusCode) |
| 33 | + return Array.Empty<byte>(); |
| 34 | + CharacteristicsJSON? chars = JsonSerializer.Deserialize<CharacteristicsJSON>(msg.Content.ReadAsStream()); |
| 35 | + if (chars == null || chars.Characteristics.Length == 0) |
| 36 | + return Array.Empty<byte>(); |
| 37 | + LastValue = MapValue(chars.Characteristics[0].Value); |
| 38 | + return LastValue; |
| 39 | + } |
| 40 | + |
| 41 | + protected byte[] MapValue(JsonElement? value) |
| 42 | + { |
| 43 | + if (value.HasValue) |
| 44 | + { |
| 45 | + if (value.Value.ValueKind == JsonValueKind.String) |
| 46 | + return Convert.FromBase64String(value.Value.GetString() ?? string.Empty); |
| 47 | + else |
| 48 | + throw new ArgumentException("Value Mismatch " + value); |
| 49 | + } |
| 50 | + else |
| 51 | + return Array.Empty<byte>(); |
| 52 | + } |
| 53 | + |
| 54 | + internal override void FireUpdate(JsonElement? value) |
| 55 | + { |
| 56 | + byte[] newVal = MapValue(value); |
| 57 | + if (Updated != null) |
| 58 | + Updated.Invoke(service, this, newVal); |
| 59 | + LastValue = newVal; |
| 60 | + } |
| 61 | + |
| 62 | + public byte[] LastValue { get; set; } |
| 63 | + public float? MaxLength => _json.MaxLength; |
| 64 | + public float? MaxDataLength => _json.MaxDataLength; |
| 65 | + } |
| 66 | +} |
0 commit comments