InfluxWriter.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using InfluxDB.LineProtocol.Client;
  6. using InfluxDB.LineProtocol.Payload;
  7. using NLog;
  8. using OpenHardwareMonitor.Hardware;
  9. namespace OhmGraphite
  10. {
  11. public class InfluxWriter : IWriteMetrics
  12. {
  13. private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
  14. private readonly InfluxConfig _config;
  15. private readonly string _localHost;
  16. public InfluxWriter(InfluxConfig config, string localHost)
  17. {
  18. _config = config;
  19. _localHost = localHost;
  20. }
  21. public async Task ReportMetrics(DateTime reportTime, IEnumerable<ReportedValue> sensors)
  22. {
  23. var payload = new LineProtocolPayload();
  24. var client = new LineProtocolClient(_config.Address, _config.Db, _config.User, _config.Password);
  25. foreach (var point in sensors.Select(x => NewPoint(reportTime, x)))
  26. {
  27. payload.Add(point);
  28. }
  29. var result = await client.WriteAsync(payload);
  30. if (!result.Success)
  31. {
  32. Logger.Error("Influxdb encountered an error: {0}", result.ErrorMessage);
  33. }
  34. }
  35. private LineProtocolPoint NewPoint(DateTime reportTime, ReportedValue sensor)
  36. {
  37. var sensorType = Enum.GetName(typeof(SensorType), sensor.SensorType);
  38. var tags = new Dictionary<string, string>()
  39. {
  40. {"host", _localHost},
  41. {"app", "ohm"},
  42. {"hardware", sensor.Hardware},
  43. {"hardware_type", Enum.GetName(typeof(HardwareType), sensor.HardwareType)},
  44. {"identifier", sensor.Identifier },
  45. {"sensor", sensor.Sensor},
  46. };
  47. var fields = new Dictionary<string, object>()
  48. {
  49. {"value", sensor.Value},
  50. {"sensor_index", sensor.SensorIndex}
  51. };
  52. return new LineProtocolPoint(sensorType, fields, tags, reportTime.ToUniversalTime());
  53. }
  54. }
  55. }