Fully working plot, server, and sensor with timestamps

This commit is contained in:
2025-12-20 21:10:43 +01:00
parent 552055fd0a
commit ac32052a41
2 changed files with 39 additions and 18 deletions

26
main.go
View File

@@ -12,20 +12,28 @@ import (
)
var dataFile *os.File
var startTime time.Time
var berlinTZ *time.Location
type VoltageData struct {
Voltage float64 `json:"voltage"`
}
func init() {
var err error
berlinTZ, err = time.LoadLocation("Europe/Berlin")
if err != nil {
log.Fatalf("Failed to load Berlin timezone: %v", err)
}
}
func initDataFile() {
// Ensure the data/ directory exists
if err := os.MkdirAll("data", os.ModePerm); err != nil {
log.Fatalf("Failed to create data directory: %v", err)
}
// Generate a filename with timestamp
filename := filepath.Join("data", fmt.Sprintf("voltages_%s.csv", time.Now().Format("20060102_150405")))
// Generate a filename with timestamp in Berlin local time
filename := filepath.Join("data", fmt.Sprintf("voltages_%s.csv", time.Now().In(berlinTZ).Format("20060102_150405")))
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("Failed to open data file: %v", err)
@@ -35,9 +43,7 @@ func initDataFile() {
log.Printf("Logging voltage data to %s\n", filename)
// Write CSV header
_, _ = dataFile.WriteString("time_s,voltage\n")
startTime = time.Now()
_, _ = dataFile.WriteString("timestamp,voltage\n")
}
func handler(w http.ResponseWriter, r *http.Request) {
@@ -60,15 +66,15 @@ func handler(w http.ResponseWriter, r *http.Request) {
return
}
// Compute relative time
relTime := time.Since(startTime).Seconds()
// Get current timestamp in Berlin
timestamp := time.Now().In(berlinTZ).Format("2006-01-02 15:04:05.000")
// Print voltage to console
fmt.Printf("Received voltage: %f at time %.3f s\n", v.Voltage, relTime)
fmt.Printf("Received voltage: %f at %s\n", v.Voltage, timestamp)
// Append CSV line to file
if dataFile != nil {
if _, err := dataFile.WriteString(fmt.Sprintf("%.3f,%.6f\n", relTime, v.Voltage)); err != nil {
if _, err := dataFile.WriteString(fmt.Sprintf("%s,%.6f\n", timestamp, v.Voltage)); err != nil {
log.Printf("Failed to write to file: %v", err)
}
}