edenic-exporter/Program.cs

238 lines
8.4 KiB
C#
Raw Normal View History

2024-08-17 01:46:22 +00:00
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
2024-08-17 01:54:33 +00:00
using Microsoft.AspNetCore.Http;
2024-08-17 01:46:22 +00:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Prometheus;
2024-08-17 03:00:06 +00:00
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Linq;
2024-08-17 01:46:22 +00:00
2024-08-17 01:54:33 +00:00
namespace PrometheusExporterEdenic
2024-08-17 01:46:22 +00:00
{
2024-08-17 23:57:42 +00:00
public class Device
{
public string id { get; set; }
public string name { get; set; }
public string label { get; set; }
// Add other properties as needed
}
2024-08-17 03:00:06 +00:00
public class ApiClient
{
private readonly HttpClient _client;
private readonly string _authToken;
2024-08-17 23:57:42 +00:00
private readonly string _orgid;
2024-08-18 01:01:27 +00:00
private readonly string _apimainurl = "https://api.edenic.io/api/v1";
2024-08-18 00:55:16 +00:00
private string _devicename;
public string DeviceName => _devicename;
2024-08-18 00:55:16 +00:00
public string DeviceId { get; private set; }
2024-08-18 01:18:59 +00:00
public int ph { get; private set; }
public int temperature { get; private set; }
public int ec { get; private set; }
2024-08-21 23:00:35 +00:00
2024-08-18 00:55:16 +00:00
public async Task InitializeAsync()
{
DeviceId = await GetDeviceIdByName(_devicename);
}
2024-08-17 03:00:06 +00:00
2024-08-18 00:55:16 +00:00
public ApiClient(string authToken, string orgID, string devicename)
2024-08-17 03:00:06 +00:00
{
_client = new HttpClient();
_authToken = authToken;
2024-08-17 23:57:42 +00:00
_orgid = orgID;
2024-08-18 00:55:16 +00:00
_devicename = devicename;
2024-08-21 23:00:35 +00:00
_client.DefaultRequestHeaders.Authorization =
2024-08-17 03:00:06 +00:00
new AuthenticationHeaderValue(_authToken);
}
2024-08-17 23:57:42 +00:00
public async Task<dynamic> MakeApiRequest<T>(string path)
2024-08-17 03:00:06 +00:00
{
try
{
2024-08-18 01:01:27 +00:00
HttpResponseMessage response = await _client.GetAsync($"{_apimainurl}{path}");
Console.WriteLine($"Request send to: {_apimainurl}{path}");
2024-08-21 23:00:35 +00:00
2024-08-17 03:00:06 +00:00
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
2024-08-17 23:57:42 +00:00
return JsonSerializer.Deserialize<dynamic>(content); }
2024-08-17 03:00:06 +00:00
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;
}
}
2024-08-17 23:57:42 +00:00
public async Task<string> GetDeviceIdByName(string name)
{
2024-08-18 00:55:16 +00:00
try
{
2024-08-18 01:01:27 +00:00
dynamic result = await MakeApiRequest<object>($"/device/{_orgid}");
2024-08-18 00:55:16 +00:00
string jsonString = result.ToString(); // Convert dynamic to string
Console.WriteLine($"Raw JSON: {jsonString}"); // Debug output
var devices = JsonSerializer.Deserialize<List<Device>>(jsonString);
Console.WriteLine($"Deserialized {devices.Count} devices"); // Debug output
var targetDevice = devices.FirstOrDefault(d => d.label == name);
if (targetDevice != null)
{
Console.WriteLine($"Found device: {targetDevice.label}, ID: {targetDevice.id}"); // Debug output
return targetDevice.id;
}
else
{
Console.WriteLine($"No device found with label: {name}"); // Debug output
return null;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in GetDeviceIdByName: {ex.Message}"); // Debug output
return null;
}
2024-08-17 23:57:42 +00:00
}
2024-08-18 01:18:59 +00:00
public async Task GetTelemetry()
2024-08-18 01:01:27 +00:00
{
try
{
dynamic result = await MakeApiRequest<object>($"/telemetry/{DeviceId}");
2024-08-18 01:18:59 +00:00
string jsonString = result.ToString();
2024-08-18 01:01:27 +00:00
Console.WriteLine($"Raw JSON: {jsonString}"); // Debug output
2024-08-18 01:18:59 +00:00
using (JsonDocument doc = JsonDocument.Parse(jsonString))
{
JsonElement root = doc.RootElement;
ph = ExtractValue(root, "ph");
temperature = ExtractValue(root, "temperature");
ec = ExtractValue(root, "electrical_conductivity");
Console.WriteLine($"Extracted values - pH: {ph/100.0}, Temperature: {temperature/100.0}, EC: {ec/100.0}");
}
2024-08-18 01:01:27 +00:00
}
catch (Exception ex)
{
2024-08-18 01:18:59 +00:00
Console.WriteLine($"Error in GetTelemetry: {ex.Message}");
}
}
private int ExtractValue(JsonElement root, string key)
{
if (root.TryGetProperty(key, out JsonElement property) &&
property.GetArrayLength() > 0 &&
property[0].TryGetProperty("value", out JsonElement valueElement))
{
string valueString = valueElement.GetString();
if (!string.IsNullOrEmpty(valueString))
{
if (float.TryParse(valueString, out float floatValue))
{
return (int)(floatValue * 100); // Convert to int, preserving two decimal places
}
else
{
Console.WriteLine($"Error: Unable to parse {key} value: {valueString}");
}
}
else
{
Console.WriteLine($"Error: {key} value is empty");
}
}
else
{
Console.WriteLine($"Error: {key} not found or invalid");
2024-08-18 01:01:27 +00:00
}
2024-08-18 01:18:59 +00:00
return 0; // Default value
2024-08-18 01:01:27 +00:00
}
2024-08-17 03:00:06 +00:00
}
2024-08-17 01:46:22 +00:00
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
2024-08-17 03:00:06 +00:00
2024-08-17 01:46:22 +00:00
app.UseMetricServer();
app.UseHttpMetrics();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Open /metrics");
});
});
var phGauge = Metrics.CreateGauge("edenic_ph", "Edenic ph", new GaugeConfiguration
{
LabelNames = new[] { "device_name" }
});
var temperatureGauge = Metrics.CreateGauge("edenic_temperature", "Edenic temperature", new GaugeConfiguration
{
LabelNames = new[] { "device_name" }
});
var ecGauge = Metrics.CreateGauge("edenic_ec", "Edenic EC", new GaugeConfiguration
{
LabelNames = new[] { "device_name" }
});
2024-08-17 03:00:06 +00:00
2024-08-18 00:55:16 +00:00
string EDENIC_API_TOKEN = Environment.GetEnvironmentVariable("EDENIC_API_TOKEN");
string EDENIC_ORG_ID = Environment.GetEnvironmentVariable("EDENIC_ORG_ID");
string EDENIC_DEVICENAME = Environment.GetEnvironmentVariable("EDENIC_DEVICENAME");
ApiClient client = new ApiClient(EDENIC_API_TOKEN, EDENIC_ORG_ID, EDENIC_DEVICENAME);
2024-08-17 23:57:42 +00:00
2024-08-17 01:46:22 +00:00
Task.Run(async () =>
{
2024-08-18 00:55:16 +00:00
await client.InitializeAsync();
Console.WriteLine($"Device ID: {client.DeviceId}");
2024-08-17 01:46:22 +00:00
while (true)
{
2024-08-18 01:18:59 +00:00
await client.GetTelemetry();
phGauge.WithLabels(client.DeviceName).Set(client.ph / 100.0);
temperatureGauge.WithLabels(client.DeviceName).Set(client.temperature / 100.0);
ecGauge.WithLabels(client.DeviceName).Set(client.ec / 100.0);
2024-08-18 01:27:01 +00:00
await Task.Delay(60000);
2024-08-17 01:46:22 +00:00
}
});
}
}
}