First functioning draft
This commit is contained in:
54
InfluxDataService.cs
Normal file
54
InfluxDataService.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using InfluxDB.Client;
|
||||
|
||||
public class InfluxDataService
|
||||
{
|
||||
private readonly string _url;
|
||||
private readonly string _token;
|
||||
private readonly string _org;
|
||||
private readonly string _bucket;
|
||||
|
||||
public InfluxDataService(string url, string token, string org, string bucket)
|
||||
{
|
||||
_url = url;
|
||||
_token = token;
|
||||
_org = org;
|
||||
_bucket = bucket;
|
||||
}
|
||||
|
||||
public async Task<float> GetLatestTemperatureAsync()
|
||||
{
|
||||
// Connect to the InfluxDB container
|
||||
using var client = new InfluxDBClient(_url, _token);
|
||||
var queryApi = client.GetQueryApi();
|
||||
|
||||
// This is a standard Flux query to get the last recorded value in the last 15 mins.
|
||||
// You will need to change "_measurement" and "_field" to match your setup.
|
||||
string flux = $@"
|
||||
from(bucket: ""{_bucket}"")
|
||||
|> range(start: -15m)
|
||||
|> filter(fn: (r) => r[""_measurement""] == ""LoRa_Test_DB_2"")
|
||||
|> filter(fn: (r) => r[""_field""] == ""temperature"")
|
||||
|> last()";
|
||||
|
||||
try
|
||||
{
|
||||
var tables = await queryApi.QueryAsync(flux, _org);
|
||||
|
||||
// Check if we actually got data back
|
||||
if (tables != null && tables.Any() && tables[0].Records.Any())
|
||||
{
|
||||
var record = tables[0].Records[0];
|
||||
return Convert.ToSingle(record.GetValue());
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Error querying InfluxDB: {ex.Message}");
|
||||
}
|
||||
|
||||
return 0f; // Fallback value if query fails or no data is found
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user