Better makefile, plotting, saving the data, and cleanup

This commit is contained in:
2025-12-20 20:39:35 +01:00
parent 0efab1c8b3
commit ce9b819b18
7 changed files with 103 additions and 77 deletions

47
main.go
View File

@@ -1,12 +1,39 @@
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"time"
)
var dataFile *os.File
type VoltageData struct {
Voltage float64 `json:"voltage"`
}
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.txt", time.Now().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)
}
dataFile = file
log.Printf("Logging voltage data to %s\n", filename)
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
@@ -20,13 +47,31 @@ func handler(w http.ResponseWriter, r *http.Request) {
}
defer r.Body.Close()
fmt.Println("Received:", string(body))
// Parse JSON
var v VoltageData
if err := json.Unmarshal(body, &v); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
// Print voltage to console
fmt.Println("Received voltage:", v.Voltage)
// Append voltage number to file
if dataFile != nil {
if _, err := dataFile.WriteString(fmt.Sprintf("%f\n", v.Voltage)); err != nil {
log.Printf("Failed to write to file: %v", err)
}
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}
func main() {
initDataFile()
defer dataFile.Close()
http.HandleFunc("/data", handler)
addr := ":8080"