diff --git a/main.go b/main.go index 2fa9b2a..4b2e090 100644 --- a/main.go +++ b/main.go @@ -88,6 +88,16 @@ func readRegs(client modbus.Client, start, qty uint16) { } } +func scrape(client modbus.Client) { + start := time.Now() + scrapeStart.SetToCurrentTime() + readRegs(client, 5000, 50) + readRegs(client, 5100, 50) + scrapeEnd.SetToCurrentTime() + scrapeDuration.Set(time.Since(start).Seconds()) + scrapeCounter.Inc() +} + func main() { flag.Parse() scrapeIntervalGauge.Set(float64(*scrapeInterval)) @@ -117,10 +127,9 @@ func main() { io.Copy(conn, sgc) }() - // HTTP stuff + // HTTP setup http.Handle("/metrics", promhttp.Handler()) http.HandleFunc("/", statusHandler) - go http.ListenAndServe(*httpAddr, nil) // Modbus scrape loop handler := modbus.NewTCPClientHandler(ln.Addr().String()) @@ -128,17 +137,10 @@ func main() { handler.Connect() defer handler.Close() client := modbus.NewClient(handler) - - ticker := time.Tick(*scrapeInterval) - for { - start := time.Now() - scrapeStart.SetToCurrentTime() - readRegs(client, 5000, 50) - readRegs(client, 5100, 50) - scrapeEnd.SetToCurrentTime() - scrapeDuration.Set(time.Since(start).Seconds()) - scrapeCounter.Inc() - - <-ticker + scrape(client) + // Start http interface only after first successful scrape + go http.ListenAndServe(*httpAddr, nil) + for range time.Tick(*scrapeInterval) { + scrape(client) } }