Skip to content

Instantly share code, notes, and snippets.

@taiyoh
Created December 27, 2015 06:17
Show Gist options
  • Save taiyoh/eb7d00b1503d2694dc93 to your computer and use it in GitHub Desktop.
Save taiyoh/eb7d00b1503d2694dc93 to your computer and use it in GitHub Desktop.
package main
import (
mkr "github.com/mackerelio/mackerel-client-go"
"github.com/taiyoh/go-cm160"
"log"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
volt := 100
recch := make(chan *cm160.Record)
client := mkr.NewClient("<api-key>")
device := cm160.Open(recch)
defer device.Close()
log.Println("device initialized")
// signal handling
sigchan := make(chan bool)
go func() {
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
caughtsig := <-ch
log.Printf("signal caught: %#v exiting\n", caughtsig)
sigchan <- true
}()
log.Println("signal handling is ready")
loc, _ := time.LoadLocation("Asia/Tokyo")
postToMackerel := func(record *cm160.Record) {
t := time.Date(record.Year, time.Month(record.Month), record.Day, record.Hour, record.Minute, time.Now().Second(), 0, loc)
err := client.PostHostMetricValuesByHostID("<host-id>", []*mkr.MetricValue{
&mkr.MetricValue{
Name: "inhouse.energy.amps",
Time: t.Unix(),
Value: record.Amps,
},
})
if err != nil {
log.Printf("mackerel error: %#v", err)
}
}
go func() {
for {
select {
case <-sigchan:
log.Println("stop running")
device.Stop()
break
case record := <-recch:
if record.IsLive {
log.Printf("live record amps: %#v\n", record.Amps)
} else {
log.Printf("not live at %d-%02d-%02d %02d:%02d amps: %#v\n", record.Year, record.Month, record.Day, record.Hour, record.Minute, record.Amps)
}
go postToMackerel(record)
}
time.Sleep(10 * time.Millisecond)
}
}()
device.Run(volt)
log.Println("exit process")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment