49 lines
1.4 KiB
C#
49 lines
1.4 KiB
C#
using System.Net;
|
|
using System.Text.Json.Nodes;
|
|
using Flurl.Http;
|
|
using Flurl.Http.Content;
|
|
using static System.Net.Http.HttpMethod;
|
|
|
|
namespace InnovEnergy.Lib.Victron.VictronVRM;
|
|
|
|
public static class FlurlExtensions
|
|
{
|
|
|
|
public static async Task<JsonNode> TryGetJson(this IFlurlRequest request)
|
|
{
|
|
var stream = await TryRequest(request, Get).ReceiveStream();
|
|
return JsonNode.Parse(stream)!;
|
|
}
|
|
|
|
public static async Task<JsonNode> TryPostJson(this IFlurlRequest request, JsonObject? content = null)
|
|
{
|
|
var stream = await TryRequest(request, Post, content).ReceiveStream();
|
|
return JsonNode.Parse(stream)!;
|
|
}
|
|
|
|
private static async Task<IFlurlResponse> TryRequest(this IFlurlRequest request, HttpMethod verb, JsonObject? data = null)
|
|
{
|
|
var jsonContent = data is null
|
|
? null
|
|
: new CapturedJsonContent(data.ToJsonString());
|
|
|
|
var delayMs = 50;
|
|
|
|
while (true)
|
|
{
|
|
try
|
|
{
|
|
return await request.SendAsync(verb, jsonContent);
|
|
}
|
|
catch (FlurlHttpException e) when (e.StatusCode == (Int32)HttpStatusCode.TooManyRequests)
|
|
{
|
|
if (delayMs > 2000)
|
|
throw;
|
|
|
|
await Task.Delay(delayMs);
|
|
delayMs = delayMs * 2 + Random.Shared.Next() % 4;
|
|
}
|
|
}
|
|
|
|
}
|
|
} |