Skip to content

Instantly share code, notes, and snippets.

@kontza
Created December 21, 2023 08:38
Show Gist options
  • Save kontza/e578e740f691082d0b5802d2167d8c00 to your computer and use it in GitHub Desktop.
Save kontza/e578e740f691082d0b5802d2167d8c00 to your computer and use it in GitHub Desktop.
Injecting data into Influx from a pre-named CSV file. Downsampled to 5 minutes.
package main
import (
"bufio"
"context"
"log"
"os"
"strconv"
"strings"
"time"
influxdb2 "github.com/influxdata/influxdb-client-go/v2"
"github.com/influxdata/influxdb-client-go/v2/api/write"
)
var count int = 0
var totalCount int = 0
var previousTime time.Time = time.Unix(1704067200000, 0)
func storeMeasurement(payload string) {
parts := strings.Split(payload, ",")
var timestamp int64
timestamp, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil {
log.Printf("Failed to parse '%s': %v", parts[0], err)
return
}
diff := previousTime.Sub(time.Unix(timestamp, 0))
totalCount++
if time.Duration(diff.Minutes()) > 5 {
count++
previousTime = time.Unix(timestamp, 0)
storeData(timestamp, parts[1])
}
}
func storeData(timestamp int64, temperature string) {
client := influxdb2.NewClient("http://localhost:8086", "influxdb-access-token")
writeAPI := client.WriteAPIBlocking("your-organisation", "your-bucket")
tags := map[string]string{
"location": "Garage",
}
temperatureFloat, err := strconv.ParseFloat(temperature, 64)
if err != nil {
log.Printf("Failed to parse '%s'", temperature)
return
}
fields := map[string]interface{}{
"device": "28f501ea030000fc",
"temperature": temperatureFloat,
}
point := write.NewPoint("temperatures", tags, fields, time.Unix(timestamp, 0))
if err := writeAPI.WritePoint(context.Background(), point); err != nil {
log.Printf("Failed to write data: %v", err)
}
}
func main() {
myfile, err := os.Open("result_set.csv")
if err != nil {
log.Fatal("Failed to open file:", err)
}
defer myfile.Close()
scanner := bufio.NewScanner(myfile)
for scanner.Scan() {
storeMeasurement(scanner.Text())
}
log.Printf("%d measurements stored, total was %d", count, totalCount)
if err := scanner.Err(); err != nil {
log.Fatal("Failed to read file:", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment