Created
January 28, 2020 15:18
-
-
Save freeekanayaka/6880d1ae07561f79e975c33755bd94bf to your computer and use it in GitHub Desktop.
Sketch pulse oximeter with SQLite and Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"io" | |
"log" | |
"math/rand" | |
"net/http" | |
"time" | |
_ "github.com/mattn/go-sqlite3" | |
) | |
func getDatabase() *sql.DB { | |
db, err := sql.Open("sqlite3", "oximeter.db") | |
if err != nil { | |
log.Fatal(err) | |
} | |
_, err = db.Exec( | |
"CREATE TABLE IF NOT EXISTS saturation " + | |
"(value FLOAT, time DATETIME DEFAULT CURRENT_TIMESTAMP)", | |
) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return db | |
} | |
func measureSaturation() float64 { | |
return 95.0 + 5*rand.Float64() | |
} | |
func persistSaturation(db *sql.DB, value float64) { | |
if _, err := db.Exec("INSERT INTO saturation (value) VALUES(?)", value); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func retrieveAverageSaturation(db *sql.DB, tail time.Duration) float64 { | |
row := db.QueryRow( | |
"SELECT avg(value) FROM saturation WHERE time >= ?", time.Now().Add(-tail)) | |
var average float64 | |
if err := row.Scan(&average); err != nil { | |
log.Fatal(err) | |
} | |
return average | |
} | |
func main() { | |
rand.Seed(time.Now().UTC().UnixNano()) | |
db := getDatabase() | |
go func() { | |
for { | |
persistSaturation(db, measureSaturation()) | |
time.Sleep(time.Second) | |
} | |
}() | |
http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
tail, err := time.ParseDuration(r.URL.Query()["tail"][0]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
io.WriteString(w, fmt.Sprintf("%f\n", retrieveAverageSaturation(db, tail))) | |
})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment