wsdashdemo/main.go

81 lines
1.3 KiB
Go
Raw Normal View History

2020-01-20 14:37:46 +00:00
package main
import (
"encoding/csv"
"github.com/gorilla/websocket"
"io"
"log"
"net/http"
"os"
"strconv"
"time"
)
type dashData struct {
RPM int `json:"rpm"`
Speed int `json:"speed"`
PSI float64 `json:"psi"`
}
// Process the data log at startup
func load_data(filename string) []dashData {
var d []dashData
f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
r := csv.NewReader(f)
for {
row, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
var e dashData
e.RPM, _ = strconv.Atoi(row[0])
e.Speed, _ = strconv.Atoi(row[2])
e.PSI, _ = strconv.ParseFloat(row[1], 64)
d = append(d, e)
}
return d
}
2020-01-20 14:54:56 +00:00
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
2020-01-20 14:37:46 +00:00
func main() {
http.HandleFunc("/ws", subscribe)
log.Fatal(http.ListenAndServe("localhost:9888", nil))
}
func subscribe(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
// Load data set
d := load_data("fin.csv")
iterator := 0
for {
if iterator == len(d) {
iterator = 0
}
err := c.WriteJSON(d[iterator])
if err != nil {
// Conection dropped or otherwise
log.Printf("Connection failed.")
return
}
time.Sleep(100 * time.Millisecond)
2020-01-20 14:58:51 +00:00
iterator++
2020-01-20 14:37:46 +00:00
}
}