From 318bfe993c97ee728cd8d6fb90c988078506888c Mon Sep 17 00:00:00 2001 From: Patrick Ritchie Date: Wed, 19 Apr 2023 00:22:49 -0400 Subject: [PATCH] Added example for writing MTConnect Observations to an InfluxDB database --- docs/InfluxDB.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 docs/InfluxDB.md diff --git a/docs/InfluxDB.md b/docs/InfluxDB.md new file mode 100644 index 00000000..2fe11a0e --- /dev/null +++ b/docs/InfluxDB.md @@ -0,0 +1,48 @@ +# MTConnect > InfluxDB +Uses the MTConnect.NET MTConnectHttpClient class to read from an MTConnect Agent and write that data to an InfluxDB database + +## Example +```c# +using InfluxDB.Client; +using InfluxDB.Client.Api.Domain; +using InfluxDB.Client.Writes; +using MTConnect.Clients; +using MTConnect.Observations; +using MTConnect.Streams; + +var influxServer = "https://eastus-1.azure.cloud2.influxdata.com"; +var influxToken = "klajsdfdslkfjdslkfjsdlkfjlsdkjflakdsjf"; +var influxOrganization = "example"; + +// Setup InfluxDB Client +var influxClient = new InfluxDBClient(influxServer, influxToken); + +// Setup MTConnect Client (over HTTP) +var mtconnectClient = new MTConnectHttpClient("http://localhost:5000"); +mtconnectClient.OnCurrentReceived += ObservationsReceived; +mtconnectClient.OnSampleReceived += ObservationsReceived; +mtconnectClient.Start(); + +Console.ReadLine(); + +mtconnectClient.Stop(); + +void ObservationsReceived(object sender, IStreamsResponseDocument response) +{ + using (var write = influxClient.GetWriteApi()) + { + var records = new List(); + + foreach (var observation in response.GetObservations()) + { + var key = $"{observation.DeviceUuid}.{observation.DataItemId}"; + records.Add(PointData.Measurement(key) + .Field("value", observation.GetValue(ValueKeys.Result)) + .Timestamp(observation.Timestamp, WritePrecision.Us)); + } + + // Write Records + write.WritePoints(records, "MTConnect.Streams", influxOrganization); + } +} +```