Skip to content

Instantly share code, notes, and snippets.

@riston
Created December 31, 2015 13:42
Show Gist options
  • Save riston/d2c67adb386ad1a98f04 to your computer and use it in GitHub Desktop.
Save riston/d2c67adb386ad1a98f04 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/d2r2/go-dht"
)
var (
BaseURL = "http://api-m2x.att.com"
)
// Value is a current sensor reading
type Value struct {
Time time.Time `json:"timestamp"`
Value string `json:"value"`
}
// Sensor is a structure which contains multiple temperature and humidity values
type Sensor struct {
Temperature []Value `json:"Temperature"`
Humidity []Value `json:"Humidity"`
}
// SensorWrap is a wrapper for the data structure
type sensorwrap struct {
time time.time `json:"timestamp"`
sensor `json:"values"`
}
func main() {
// read dht11 sensor data from pin 4, retrying 10 times in case of failure.
// you may enable "boost gpio performance" parameter, if your device is old
// as raspberry pi 1 (this will require root privileges). you can switch off
// "boost gpio performance" parameter for old devices, but it may increase
// retry attempts. play with this parameter.
temperature, humidity, _, err := dht.readdhtxxwithretry(dht.dht11, 7, true, 10)
if err != nil {
log.fatal(err)
}
current := sensorwrap{
time: time.now(),
sensor: sensor{
temperature: []value{{time.now(), fmt.sprintf("%.6f", temperature)}},
humidity: []value{{time.now(), fmt.sprintf("%.6f", humidity)}},
},
}
currentjson, err := json.marshal(current)
if err != nil {
fmt.println("could not marshal the data", err)
}
// request part begins
url := fmt.sprintf("%s/v2/devices/%s/updates", baseurl, os.getenv("m2x_device_id"))
client := &http.client{}
req, err := http.newrequest("post", url, bytes.newreader(currentjson))
if err != nil {
log.fatal(err)
}
req.header.add("x-m2x-key", os.getenv("m2x_key"))
req.header.add("content-type", "application/json")
resp, err := client.do(req)
if err != nil {
log.fatal(err)
}
defer resp.body.close()
// response output
fmt.println("status:", resp.status)
fmt.println("headers:", resp.header)
body, _ := ioutil.readall(resp.body)
fmt.println("body:", string(body))
fmt.println(currentjson)
}
# Needs root permission to read the GPIO
M2X_KEY=add-key-here
M2X_DEVICE_ID=add-key-here
*/20 * * * * root /home/pi/go/src/github.com/riston/sensors/dht_sensor >> /var/log/dht-sensor.log 2>&1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment