Building Go Applications Using InfluxDB

Prerequisites

Codes

Defining Constants

  • databaseaddr, database, username and password are required for InfluxDB.
  • hotlimit is the maximum value that the environment’s temperature can take.
  • coldlimit is the minimum value that the environment’s temperature can take.
  • deltatemp is used for temperature changing.
  • threshold is the threshold for limits.
const (
databaseaddr = "http://localhost:8086"
database = "example"
username = "root"
password = "root"
hotlimit = 45.0
coldlimit = 10.0
deltatemp = 0.1
threshold = 0.05
)

Defining InfluxDB Client

func influxDBClient() client.Client {
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr:databaseaddr ,
Username: username,
Password: password,
})
if err != nil {
log.Fatalln("Error: ", err)
}
return c
}

Changing Environment Temperature

func changeEnvironmentDegree(currentTemp float64, deltaTemp float64,limit float64) float64  {
return limit + (currentTemp-limit)*math.Exp(-0.300*deltaTemp)
}

Inserting to InfluxDB

func insertMetrics(c client.Client,temp float64,airConditionerStatus int) {
bp, err := client.NewBatchPoints(client.BatchPointsConfig{
Database: database,
Precision: "s",
})

if err != nil {
log.Fatalln("Error: ", err)
}

tags := map[string]string{
"airConditioner": "Air Conditioner 1",
}
fields := map[string]interface{}{
"degree": temp,
"airConditionerStatus":airConditionerStatus,
}
point, err := client.NewPoint(
"temperature",
tags,
fields,
time.Now(),
)
if err != nil {
log.Fatalln("Error: ", err)
}

bp.AddPoint(point)

err = c.Write(bp)
if err != nil {
log.Fatal(err)
}
}

Main

  • If the temperature is above the hot limit, the air conditioner will turn on and the limit will be Coldlimit.
  • If the temperature is below the cold limit value, the air conditioner is turned off and the limit becomes hotlimit.
  • Climate status and realtime temperature are recorded in the database.
func main() {
c := influxDBClient()

limit := coldlimit
var airConditionerStatus =1
currentTemp := 28.0

for {
currentTemp=changeEnvironmentDegree(currentTemp,deltatemp,limit)

if currentTemp >= hotlimit-threshold {
airConditionerStatus=1
limit=coldlimit
} else if currentTemp <= coldlimit+threshold {
airConditionerStatus=0
limit=hotlimit
}
fmt.Println(airConditionerStatus,currentTemp)
insertMetrics(c,currentTemp,airConditionerStatus)
time.Sleep(100 * time.Millisecond)
}
}

Conclusion

You can also find all the codes on my Github account.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store