Skip to content
Permalink
d5df70370a
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
67 lines (59 sloc) 1.69 KB
package main
import (
"fmt"
"math/rand"
"time"
)
var dataBuffer = make(map[string][]StampedReading) // Map to store readings in until they are sent
func main() {
go dataReadLoop() // Start our async read loop
client.wait.Add(1) // Make sure data and heartbeat loops don't do anything without a valid client
InitializeClient() // Get our client in this thread
go client.readIncoming() // Start our loop to read incoming messages
go dataSendLoop() // Start our async send loop
go heartbeatLoop() // Start our async heartbeat loop
select {} // Immortality
}
func dataReadLoop() { // Read data all day every day
for {
reading := readData() // TODO: error handling
for metric, value := range reading { // Put our data in the buffer
if record, found := dataBuffer[metric]; !found {
dataBuffer[metric] = []StampedReading{value}
} else {
dataBuffer[metric] = append(record, value)
}
}
time.Sleep(time.Second * dataReadPeriod)
}
}
func dataSendLoop() {
for {
time.Sleep(time.Second * dataSendPeriod)
if len(dataBuffer) == 0 { // Only send if we have data
fmt.Println("No data to send... check logs (that don't exist yet) for data reading errors (also don't exist)")
continue
}
go client.sendData(dataBuffer)
dataBuffer = make(map[string][]StampedReading)
}
}
func heartbeatLoop() {
for {
go client.sendHeartbeat()
time.Sleep(time.Second * heartbeatPeriod)
}
}
func readData() map[string]StampedReading {
// TODO: modbus
return map[string]StampedReading{
"oil.temp": {
Timestamp: int(time.Now().Unix()),
Value: rand.Intn(150),
},
"fuel.temp": {
Timestamp: int(time.Now().Unix()),
Value: rand.Intn(150),
},
}
}