1
0

InfluxWriter.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. namespace OhmGraphite
  9. {
  10. public class InfluxWriter : IWriteMetrics
  11. {
  12. private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
  13. private readonly InfluxConfig _config;
  14. private readonly string _localHost;
  15. public InfluxWriter(InfluxConfig config, string localHost)
  16. {
  17. _config = config;
  18. _localHost = localHost;
  19. }
  20. public async Task ReportMetrics(DateTime reportTime, IEnumerable<ReportedValue> sensors)
  21. {
  22. var payload = new LineProtocolPayload();
  23. var password = _config.User != null ? (_config.Password ?? "") : null;
  24. var client = new LineProtocolClient(_config.Address, _config.Db, _config.User, 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. public void Dispose()
  55. {
  56. }
  57. }
  58. }