using HaloPixelToolBox.Core.Models.Notifications;
using HaloPixelToolBox.Core.Models.Display;
using HidSharp;
using System.Collections.Concurrent;
namespace HaloPixelToolBox.Core.Utilities;
public partial class HaloPixelDevice
{
public static TimeSpan MessageDisplayDuration { get; } = TimeSpan.FromSeconds(8);
private static readonly ConcurrentDictionary<string, DeviceWriteState> writeStates = new();
private enum DeviceCommandKind { Text, DisplayMode, ScreenColor, AmbientLight, AmbientPower }
private sealed class DeviceWriteState
{
public long ResumeAt;
public long NotificationGeneration;
public long Sequence;
public HaloPixelTextCapacity? TextCapacity;
public Dictionary<DeviceCommandKind, (long Sequence, Func<HidStream, DeviceWriteState, IReadOnlyList<byte[]>> BuildPackets)> Pending { get; } = [];
}
private void WriteCommand(DeviceCommandKind kind, byte[] packet, bool clearsText = false)
=> WriteCommand(kind, (_, _) => [packet], clearsText);
private void WriteCommand(DeviceCommandKind kind,
Func<HidStream, DeviceWriteState, IReadOnlyList<byte[]>> buildPackets, bool clearsText = false)
{
var device = CurrentDevice;
if (device is null)
return;
var state = writeStates.GetOrAdd(device.DevicePath, _ => new());
lock (state)
{
if (Environment.TickCount64 < state.ResumeAt)
{
if (clearsText)
state.Pending.Remove(DeviceCommandKind.Text);
state.Pending[kind] = (++state.Sequence, buildPackets);
return;
}
using var stream = device.Open();
stream.WriteTimeout = 1000;
if (state.ResumeAt != 0)
{
state.ResumeAt = 0;
try
{
foreach (var command in state.Pending.OrderBy(command => command.Value.Sequence))
WritePackets(stream, state, command.Key, command.Value.BuildPackets);
}
finally
{
state.Pending.Clear();
}
}
WritePackets(stream, state, kind, buildPackets);
}
}
private static void WritePackets(HidStream stream, DeviceWriteState state, DeviceCommandKind kind,
Func<HidStream, DeviceWriteState, IReadOnlyList<byte[]>> buildPackets)
{
if (kind == DeviceCommandKind.DisplayMode)
state.TextCapacity = null;
var packets = buildPackets(stream, state);
for (var index = 0; index < packets.Count; index++)
{
if (kind == DeviceCommandKind.AmbientLight && index > 0)
Thread.Sleep(30);
stream.Write(packets[index]);
}
}
private static HaloPixelTextCapacity GetTextCapacity(HidStream stream, DeviceWriteState state)
{
if (state.TextCapacity is { } cached)
return cached;
stream.Write(HidPacketBuilder.BuildTextCapacityQuery());
var report = new byte[64];
var start = Environment.TickCount64;
HaloPixelTextCapacity? replyCapacity = null;
var remainingTextBytes = 0;
try
{
while (Environment.TickCount64 - start < 300)
{
stream.ReadTimeout = (int)Math.Max(1, 300 - (Environment.TickCount64 - start));
var read = stream.Read(report, 0, report.Length);
if (HidPacketBuilder.TryParseTextCapacity(report.AsSpan(0, read), out var capacity))
{
state.TextCapacity = capacity;
var reply = report.AsSpan(0, read);
if (reply[0] == 0)
reply = reply[1..];
if (replyCapacity is null)
{
replyCapacity = capacity;
remainingTextBytes = reply[9];
}
// Queries also return the previous text, potentially across several reports.
// Drain it so a later mode change cannot consume an old capacity reply.
remainingTextBytes -= ((reply[4] << 8) | reply[5]) - 4;
if (remainingTextBytes <= 0)
return capacity;
}
}
}
catch (TimeoutException) { }
if (replyCapacity is { } received)
return received;
// Older firmware may not answer the query; a single safe report still displays text.
return new(16, 50);
}
/// <summary>使用官方聊天消息通道发送原生提示,不改变普通文本或界面模式。</summary>
public MessageNotificationCapacity ShowMessageNotification(string text)
{
var device = CurrentDevice ?? throw new InvalidOperationException("未连接花再 Halo PixelBar。");
var state = writeStates.GetOrAdd(device.DevicePath, _ => new());
long generation;
MessageNotificationCapacity capacity;
lock (state)
{
using var stream = device.Open();
stream.WriteTimeout = 1000;
stream.ReadTimeout = 1000;
stream.Write(HaloPixelMessageProtocol.BuildCapacityQuery());
var report = new byte[device.GetMaxInputReportLength()];
var queryStart = Environment.TickCount64;
while (true)
{
stream.ReadTimeout = (int)Math.Max(1, 1000 - (Environment.TickCount64 - queryStart));
var read = stream.Read(report, 0, report.Length);
if (HaloPixelMessageProtocol.TryParseCapacity(report.AsSpan(0, read), out capacity))
break;
if (Environment.TickCount64 - queryStart >= 1000)
throw new IOException("花再设备未返回有效的消息通道容量。请检查设备连接。");
}
foreach (var packet in HaloPixelMessageProtocol.BuildNotification(text, capacity))
stream.Write(packet);
state.ResumeAt = Environment.TickCount64 + (long)MessageDisplayDuration.TotalMilliseconds;
generation = ++state.NotificationGeneration;
}
_ = ResumeDisplayAsync(device, state, generation);
return capacity;
}
private static async Task ResumeDisplayAsync(HidDevice device, DeviceWriteState state, long generation)
{
await Task.Delay(MessageDisplayDuration);
lock (state)
{
if (state.NotificationGeneration != generation)
return;
state.ResumeAt = 0;
try
{
if (state.Pending.Count > 0)
{
using var stream = device.Open();
stream.WriteTimeout = 1000;
foreach (var command in state.Pending.OrderBy(command => command.Value.Sequence))
WritePackets(stream, state, command.Key, command.Value.BuildPackets);
}
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR]消息提示后恢复显示失败:{ex.Message}");
}
finally
{
state.Pending.Clear();
}
}
}
}
using HaloPixelToolBox.Core.Models.Notifications;
using HaloPixelToolBox.Core.Models.Display;
using HidSharp;
using System.Collections.Concurrent;
namespace HaloPixelToolBox.Core.Utilities;
public partial class HaloPixelDevice
{
public static TimeSpan MessageDisplayDuration { get; } = TimeSpan.FromSeconds(8);
private static readonly ConcurrentDictionary<string, DeviceWriteState> writeStates = new();
private enum DeviceCommandKind { Text, DisplayMode, ScreenColor, AmbientLight, AmbientPower }
private sealed class DeviceWriteState
{
public long ResumeAt;
public long NotificationGeneration;
public long Sequence;
public HaloPixelTextCapacity? TextCapacity;
public Dictionary<DeviceCommandKind, (long Sequence, Func<HidStream, DeviceWriteState, IReadOnlyList<byte[]>> BuildPackets)> Pending { get; } = [];
}
private void WriteCommand(DeviceCommandKind kind, byte[] packet, bool clearsText = false)
=> WriteCommand(kind, (_, _) => [packet], clearsText);
private void WriteCommand(DeviceCommandKind kind,
Func<HidStream, DeviceWriteState, IReadOnlyList<byte[]>> buildPackets, bool clearsText = false)
{
var device = CurrentDevice;
if (device is null)
return;
var state = writeStates.GetOrAdd(device.DevicePath, _ => new());
lock (state)
{
if (Environment.TickCount64 < state.ResumeAt)
{
if (clearsText)
state.Pending.Remove(DeviceCommandKind.Text);
state.Pending[kind] = (++state.Sequence, buildPackets);
return;
}
using var stream = device.Open();
stream.WriteTimeout = 1000;
if (state.ResumeAt != 0)
{
state.ResumeAt = 0;
try
{
foreach (var command in state.Pending.OrderBy(command => command.Value.Sequence))
WritePackets(stream, state, command.Key, command.Value.BuildPackets);
}
finally
{
state.Pending.Clear();
}
}
WritePackets(stream, state, kind, buildPackets);
}
}
private static void WritePackets(HidStream stream, DeviceWriteState state, DeviceCommandKind kind,
Func<HidStream, DeviceWriteState, IReadOnlyList<byte[]>> buildPackets)
{
if (kind == DeviceCommandKind.DisplayMode)
state.TextCapacity = null;
var packets = buildPackets(stream, state);
for (var index = 0; index < packets.Count; index++)
{
if (kind == DeviceCommandKind.AmbientLight && index > 0)
Thread.Sleep(30);
stream.Write(packets[index]);
}
}
private static HaloPixelTextCapacity GetTextCapacity(HidStream stream, DeviceWriteState state)
{
if (state.TextCapacity is { } cached)
return cached;
stream.Write(HidPacketBuilder.BuildTextCapacityQuery());
var report = new byte[64];
var start = Environment.TickCount64;
HaloPixelTextCapacity? replyCapacity = null;
var remainingTextBytes = 0;
try
{
while (Environment.TickCount64 - start < 300)
{
stream.ReadTimeout = (int)Math.Max(1, 300 - (Environment.TickCount64 - start));
var read = stream.Read(report, 0, report.Length);
if (HidPacketBuilder.TryParseTextCapacity(report.AsSpan(0, read), out var capacity))
{
state.TextCapacity = capacity;
var reply = report.AsSpan(0, read);
if (reply[0] == 0)
reply = reply[1..];
if (replyCapacity is null)
{
replyCapacity = capacity;
remainingTextBytes = reply[9];
}
// Queries also return the previous text, potentially across several reports.
// Drain it so a later mode change cannot consume an old capacity reply.
remainingTextBytes -= ((reply[4] << 8) | reply[5]) - 4;
if (remainingTextBytes <= 0)
return capacity;
}
}
}
catch (TimeoutException) { }
if (replyCapacity is { } received)
return received;
// Older firmware may not answer the query; a single safe report still displays text.
return new(16, 50);
}
/// <summary>使用官方聊天消息通道发送原生提示,不改变普通文本或界面模式。</summary>
public MessageNotificationCapacity ShowMessageNotification(string text)
{
var device = CurrentDevice ?? throw new InvalidOperationException("未连接花再 Halo PixelBar。");
var state = writeStates.GetOrAdd(device.DevicePath, _ => new());
long generation;
MessageNotificationCapacity capacity;
lock (state)
{
using var stream = device.Open();
stream.WriteTimeout = 1000;
stream.ReadTimeout = 1000;
stream.Write(HaloPixelMessageProtocol.BuildCapacityQuery());
var report = new byte[device.GetMaxInputReportLength()];
var queryStart = Environment.TickCount64;
while (true)
{
stream.ReadTimeout = (int)Math.Max(1, 1000 - (Environment.TickCount64 - queryStart));
var read = stream.Read(report, 0, report.Length);
if (HaloPixelMessageProtocol.TryParseCapacity(report.AsSpan(0, read), out capacity))
break;
if (Environment.TickCount64 - queryStart >= 1000)
throw new IOException("花再设备未返回有效的消息通道容量。请检查设备连接。");
}
foreach (var packet in HaloPixelMessageProtocol.BuildNotification(text, capacity))
stream.Write(packet);
state.ResumeAt = Environment.TickCount64 + (long)MessageDisplayDuration.TotalMilliseconds;
generation = ++state.NotificationGeneration;
}
_ = ResumeDisplayAsync(device, state, generation);
return capacity;
}
private static async Task ResumeDisplayAsync(HidDevice device, DeviceWriteState state, long generation)
{
await Task.Delay(MessageDisplayDuration);
lock (state)
{
if (state.NotificationGeneration != generation)
return;
state.ResumeAt = 0;
try
{
if (state.Pending.Count > 0)
{
using var stream = device.Open();
stream.WriteTimeout = 1000;
foreach (var command in state.Pending.OrderBy(command => command.Value.Sequence))
WritePackets(stream, state, command.Key, command.Value.BuildPackets);
}
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR]消息提示后恢复显示失败:{ex.Message}");
}
finally
{
state.Pending.Clear();
}
}
}
}