123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package main
- import (
- "encoding/json"
- "flag"
- "fmt"
- "io/ioutil"
- "net/http"
- "strings"
- "time"
- temperature "git.snppla.net/snppla/log_temperature"
- )
- var host *string
- var db *string
- var username *string
- var password *string
- var dbHost *string
- var location *string
- var seconds *int
- type jsonPacket struct {
- Temperature_C float64
- Temperature_F float64
- }
- func checkTemperature(writer temperature.Writer) {
- resp, err := http.Get(*host)
- if err != nil {
- fmt.Println(err.Error())
- return
- }
- defer resp.Body.Close()
- contents, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- fmt.Println(err.Error())
- return
- }
- buffer := []byte(contents)
- if json.Valid(buffer) {
- var jsonPacket jsonPacket
- err := json.Unmarshal(buffer, &jsonPacket)
- if err != nil {
- fmt.Println(err.Error())
- return
- }
- if strings.Contains(strings.ToLower(string(contents)), "_f") {
- jsonPacket.Temperature_C = (jsonPacket.Temperature_F - 32) * 5 / 9
- }
- fmt.Printf("Celcius: %f. Fahrenheit: %f \n", jsonPacket.Temperature_C, jsonPacket.Temperature_F)
- measurement := temperature.Measurement{Temperature: jsonPacket.Temperature_C, BatteryState: temperature.BATT_NOT_AVAILABLE, ID: 0}
- err = writer.Write(measurement)
- if err != nil {
- fmt.Println(err.Error())
- return
- }
- }
- }
- func main() {
- host = flag.String("host", "http://localhost:80", "Http address (http://localhost:80)")
- db = flag.String("db", "temperature", "Influxdb database")
- username = flag.String("user", "", "Username")
- password = flag.String("password", "", "Password")
- dbHost = flag.String("dbHost", "http://localhost:8086", "Host to connect to")
- location = flag.String("location", "unknown", "Location of the device")
- seconds = flag.Int("delay", 1, "Number of seconds to delay between pollings")
- flag.Parse()
- locations := map[int]string{0: *location}
- writer, err := temperature.NewInfluxWriter(*db, *dbHost, *username, *password, locations)
- if err != nil {
- fmt.Println(err.Error())
- return
- }
- for {
- checkTemperature(writer)
- time.Sleep(time.Duration(*seconds) * time.Second)
- }
- }
|