This commit is contained in:
Michal 2024-08-17 04:00:06 +01:00
parent 95166c1d18
commit 9c7d7928e9
9 changed files with 123 additions and 12 deletions

View File

@ -6,9 +6,74 @@ using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Prometheus;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Linq;
namespace PrometheusExporterEdenic
{
public class ApiClient
{
private readonly HttpClient _client;
private readonly string _authToken;
public ApiClient(string authToken)
{
_client = new HttpClient();
_authToken = authToken;
_client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(_authToken);
}
public async Task<T> MakeApiRequest<T>(string url, string jsonPath)
{
try
{
HttpResponseMessage response = await _client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
using JsonDocument doc = JsonDocument.Parse(content);
JsonElement root = doc.RootElement;
// Navigate the JSON path
string[] pathSegments = jsonPath.Split('.');
JsonElement current = root;
foreach (var segment in pathSegments)
{
if (current.TryGetProperty(segment, out JsonElement next))
{
current = next;
}
else
{
throw new JsonException($"JSON path '{jsonPath}' not found in the response.");
}
}
// Convert the JsonElement to the desired type
return JsonSerializer.Deserialize<T>(current.GetRawText());
}
else
{
throw new HttpRequestException($"Error: {response.StatusCode}");
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request exception: {e.Message}");
throw;
}
catch (JsonException e)
{
Console.WriteLine($"JSON parsing exception: {e.Message}");
throw;
}
}
}
public class Program
{
public static void Main(string[] args)
@ -37,10 +102,6 @@ namespace PrometheusExporterEdenic
app.UseDeveloperExceptionPage();
}
string EDENIC_ORGID = Environment.GetEnvironmentVariable("EDENIC_ORGID") ?? "9ffb9b70-461c-11ef-92e1-85f1b2168e5a";
string EDENIC_API = Environment.GetEnvironmentVariable("EDENIC_API") ?? "ed_tjf14py97vz1cf4ugxljiiqwckxkhzim0coqogqmk1x99rfjlgi1q2vxesav4z55";
// Enable prometheus metrics
app.UseMetricServer();
app.UseHttpMetrics();
@ -54,18 +115,68 @@ namespace PrometheusExporterEdenic
});
});
// Define custom metrics
var ph = Metrics.CreateGauge("edenic_ph", "Edenic ph");
var temperature = Metrics.CreateGauge("edenic_temperature", "Edenic temperature");
var ec = Metrics.CreateGauge("edenic_ec", "Edenic EC");
Task.Run(async () =>
{
string orgID = Environment.GetEnvironmentVariable("EDENIC_ORGID") ?? "9ffb9b70-461c-11ef-92e1-85f1b2168e5a";
string authToken = Environment.GetEnvironmentVariable("EDENIC_API") ?? "ed_tjf14py97vz1cf4ugxljiiqwckxkhzim0coqogqmk1x99rfjlgi1q2vxesav4z55";
string DeviceName = Environment.GetEnvironmentVariable("EDENIC_API") ?? "The First One";
var client = new ApiClient(authToken);
while (true)
{
ph.Set(1);
temperature.Set(1);
ec.Set(1);
await Task.Delay(1000);
try
{
// Get devices
var devices = await client.MakeApiRequest<JsonElement>($"https://api.edenic.io/api/v1/device/{orgID}", "");
var targetDevice = devices.EnumerateArray()
.FirstOrDefault(d => d.GetProperty("label").GetString() == DeviceName);
if (targetDevice.ValueKind != JsonValueKind.Undefined)
{
string deviceId = targetDevice.GetProperty("id").GetString();
// Get telemetry
var telemetry = await client.MakeApiRequest<JsonElement>($"https://api.edenic.io/api/v1/telemetry/{deviceId}", "");
if (telemetry.TryGetProperty("temperature", out var tempArray) && tempArray.GetArrayLength() > 0)
{
var tempValue = tempArray[0].GetProperty("value").GetString();
if (double.TryParse(tempValue, out double tempDouble))
{
temperature.Set(tempDouble);
}
}
if (telemetry.TryGetProperty("electrical_conductivity", out var ecArray) && ecArray.GetArrayLength() > 0)
{
var ecValue = ecArray[0].GetProperty("value").GetString();
if (double.TryParse(ecValue, out double ecDouble))
{
ec.Set(ecDouble);
}
}
if (telemetry.TryGetProperty("ph", out var phArray) && phArray.GetArrayLength() > 0)
{
var phValue = phArray[0].GetProperty("value").GetString();
if (double.TryParse(phValue, out double phDouble))
{
ph.Set(phDouble);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error updating metrics: {ex.Message}");
}
await Task.Delay(15000); // Wait for 15 seconds before the next update
}
});
}

View File

@ -13,7 +13,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("DotNet.Docker")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+576ce11da69fc49bd84f117e4ef563dcddf8a397")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+95166c1d180c50f7ff979c1c159b47ace6811487")]
[assembly: System.Reflection.AssemblyProductAttribute("DotNet.Docker")]
[assembly: System.Reflection.AssemblyTitleAttribute("DotNet.Docker")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

View File

@ -1 +1 @@
b12bdd851226df3620379f067a2d97b7fa0c5ed9735ed922b09da25c217f93e3
0ba8152071c66376fc77d639d67faf462fae8128c3dce52b1d3106f76a0e8f90