Skip to content

Commit

Permalink
poll purple air instead
Browse files Browse the repository at this point in the history
  • Loading branch information
sprsquish committed Jun 19, 2024
1 parent 83fb53c commit 1c7aae1
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 86 deletions.
2 changes: 1 addition & 1 deletion src/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ func init() {
f.MakeLooper("flume", 1*time.Minute, looper.NewFlume),
f.MakeLooper("particle", 1*time.Minute, looper.NewParticle),
f.MakeLooper("updatedns", 1*time.Minute, looper.NewUpdateDNS),
f.MakeLooper("purpleair", 1*time.Minute, looper.NewPurpleAir),
}

muxer.Handle("/purpleair", f.MakeHandler("purpleair", endpoint.NewPurpleAir))
muxer.Handle("/rainforest", f.MakeHandler("rainforest", endpoint.NewRainforest))
muxer.Handle("/rachio/webhook", f.MakeHandler("rachio", endpoint.NewRachio))
}
Expand Down
85 changes: 0 additions & 85 deletions src/pkg/endpoint/purpleair.go

This file was deleted.

95 changes: 95 additions & 0 deletions src/pkg/looper/purpleair.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package looper

import (
"context"
"errors"
"fmt"
"net/url"
"time"

"github.com/rs/zerolog"
"github.com/spf13/pflag"
hm "github.com/sprsquish/housemetrics/pkg"
"github.com/sprsquish/housemetrics/pkg/store"
)

const pTimeFormat = "2006/01/02T15:04:05z"

type PurpleAir struct {
client *hm.HttpClient
logger *zerolog.Logger

host string

url *url.URL
}

var metricNames = []string{
"p_0_3_um",
"p_0_5_um",
"p_1_0_um",
"p_2_5_um",
"p_5_0_um",
"p_10_0_um",
"pm1_0_cf_1",
"pm2_5_cf_1",
"pm10_0_cf_1",
"pm1_0_atm",
"pm2_5_atm",
"pm10_0_atm",
"current_humidity",
"current_temp_f",
"pressure",
}

func NewPurpleAir(name string, flags *pflag.FlagSet, logger *zerolog.Logger, client *hm.HttpClient) hm.Looper {
p := PurpleAir{
client: client,
logger: logger,
}

flags.StringVar(&p.host, fmt.Sprintf("%s.host", name), "", "Local device host")

return &p
}

func (p *PurpleAir) Init() {
urlStr := fmt.Sprintf("http://%s/json", p.host)
url, err := url.Parse(urlStr)
if err != nil {
p.logger.Error().Err(err).Msg("failed to start")
return
}

p.url = url
}

func (p *PurpleAir) Poll(ctx context.Context, store store.Client) error {
var reading map[string]any
if err := p.client.GetJSON(ctx, p.logger, &reading, hm.URLOpt(p.url)); err != nil {
return err
}

tsAny, found := reading["DateTime"]
if !found {
return errors.New("Did not find DateTime in reading")
}

tsStr, ok := tsAny.(string)
if !ok {
return fmt.Errorf("DateTime was not a string: %#v", tsAny)
}

ts, err := time.Parse(pTimeFormat, tsStr)
if err != nil {
return err
}

for _, name := range metricNames {
if val, ok := reading[name]; ok {
store.Write(ctx, ts, name, val, nil)
}
}

return nil
}

0 comments on commit 1c7aae1

Please sign in to comment.