Innovenergy_trunk/csharp/Lib/Protocols/Modbus/Channels/PushToPullHelper.cs

42 lines
1.2 KiB
C#
Raw Permalink Normal View History

using System.Reactive.Linq;
using InnovEnergy.Lib.Utils;
2023-05-04 07:32:35 +00:00
namespace InnovEnergy.Lib.Protocols.Modbus.Channels;
public static class PushToPullHelper
{
// TODO: this is incredibly hacky, improve
public static Func<Int32, Task<IReadOnlyList<T>>> PushToPull<T>(this IObservable<T> src)
{
var buffer = new Queue<T>();
var nAvailable = src
.Do(buffer.Enqueue)
.Select(_ => buffer.Count)
2023-05-04 07:32:35 +00:00
.Publish()
.RefCount();
2023-05-04 07:32:35 +00:00
nAvailable.SelectError()
.Subscribe(e => e.WriteLine());
async Task<IReadOnlyList<T>> Read(Int32 n)
{
2023-05-04 07:32:35 +00:00
Console.WriteLine($"requesting {n}");
var available = buffer.Count;
if (available < n)
available = await nAvailable.FirstOrDefaultAsync(a => a >= n);
if (available < n)
throw new Exception("Connection closed");
return Enumerable
.Range(0, n)
.Select(_ => buffer.Dequeue())
.ToArray(n);
}
return Read;
}
}