Browse Source

Init

master
sipp11 7 years ago
commit
d4efa76643
  1. 46
      helper.go
  2. 8
      home.html
  3. 28
      model.go
  4. 96
      read_item.go
  5. 7
      readme.md
  6. 66
      router.go

46
helper.go

@ -0,0 +1,46 @@
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/expression"
)
// GetDevices is to get all devices we know
func GetDevices(svc *dynamodb.DynamoDB) (*dynamodb.ScanOutput, error) {
proj := expression.NamesList(
expression.Name("device"),
expression.Name("name"))
expr, _ := expression.NewBuilder().WithProjection(proj).Build()
// Build the query input parameters
params := &dynamodb.ScanInput{
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
ProjectionExpression: expr.Projection(),
TableName: aws.String("iot-item"),
}
return svc.Scan(params)
}
// GetHistory is a query history for any device
func GetHistory(svc *dynamodb.DynamoDB, deviceID string, limit int64) (*dynamodb.QueryOutput, error) {
keyCond := expression.Key("device").Equal(expression.Value(deviceID))
qProj := expression.NamesList(expression.Name("device"), expression.Name("timestamp"), expression.Name("data"))
qBuilder := expression.NewBuilder().WithKeyCondition(keyCond).WithProjection(qProj)
qExpression, _ := qBuilder.Build()
queryInput := &dynamodb.QueryInput{
KeyConditionExpression: qExpression.KeyCondition(),
ProjectionExpression: qExpression.Projection(),
ExpressionAttributeNames: qExpression.Names(),
ExpressionAttributeValues: qExpression.Values(),
ScanIndexForward: aws.Bool(false),
TableName: aws.String("iot-logger"),
Limit: aws.Int64(limit),
}
return svc.Query(queryInput)
}

8
home.html

@ -0,0 +1,8 @@
<html>
<header>
<title>Home</title>
</header>
<body>
<h1>{{ query }}</h1>
</body>
</html>

28
model.go

@ -0,0 +1,28 @@
package main
// Device struct for store device data from iot-item table
type Device struct {
Device string `json:"device"`
Name string `json:"name"`
}
// Create structs to hold info about new item
type ItemInfo struct {
Firmware string `json:"firmware"`
Sensor string `json:"sensor"`
}
type ItemFloraData struct {
Battery int `json:"battery"`
Light int `json:"light"`
Conductivity float32 `json:"conductivity"`
Moisture float32 `json:"moisture"`
Temperature float32 `json:"temperature"`
}
type Item struct {
Device string `json:"device"`
Timestamp string `json:"timestamp"`
Info ItemInfo `json:"info"`
Data ItemFloraData `json:"data"`
}

96
read_item.go

@ -0,0 +1,96 @@
package main
import (
"io"
"log"
"net/http"
"github.com/flosch/pongo2"
"github.com/gorilla/mux"
)
var tplHome = pongo2.Must(pongo2.FromFile("home.html"))
func indexHandler(w http.ResponseWriter, r *http.Request) {
// Execute the template per HTTP request
err := tplHome.ExecuteWriter(pongo2.Context{"query": "dddd"}, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
// A very simple health check.
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
// In the future we could report back on the status of our DB, or our cache
// (e.g. Redis) by performing a simple PING, and include them in the response.
io.WriteString(w, `{"alive": true}`)
}
func main() {
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
// sess, err := session.NewSession(&aws.Config{
// Region: aws.String("ap-southeast-1")},
// )
// Create DynamoDB client
/* svc := dynamodb.New(sess)
devices, err := GetDevices(svc)
if err != nil {
fmt.Println("Got error unmarshalling:")
fmt.Println(err.Error())
os.Exit(1)
}
for _, i := range devices.Items {
device := Device{}
err := dynamodbattribute.UnmarshalMap(i, &device)
fmt.Printf(":: Name: %+v (%+v)\n", device.Name, device.Device)
result, err := GetHistory(svc, device.Device, 2)
// Make the DynamoDB Query API call
// fmt.Printf("result count item: %+v|%+v|", result.Count, result.ScannedCount)
for _, i := range result.Items {
item := Item{}
err = dynamodbattribute.UnmarshalMap(i, &item)
if err != nil {
fmt.Println("Got error unmarshalling:")
fmt.Println(err.Error())
os.Exit(1)
}
// fmt.Println("Found item:")
fmt.Println(" > Timestamp: ", item.Timestamp,
"Data == Temp: ", item.Data.Temperature,
" | moisure: ", item.Data.Moisture)
}
} */
// func main() {
// session, err := r.Connect(r.ConnectOpts{
// Address: "localhost:28015",
// Database: "rtcom",
// })
// if err != nil {
// log.Panic(err.Error())
// }
// router := NewRouter()
// router.Handle("channel add", addChannel)
// router.Handle("channel subscribe", subscribeChannel)
// http.Handle("/", router)
// http.ListenAndServe(":4000", nil)
r := mux.NewRouter()
// r.HandleFunc("/", HomeHandler)
// r.HandleFunc("/products", ProductsHandler)
// r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT")
// r.HandleFunc("/authors", handler).Queries("surname", "{surname}")
r.HandleFunc("/health", healthCheckHandler)
r.HandleFunc("/", indexHandler)
log.Fatal(http.ListenAndServe(":8000", r))
}

7
readme.md

@ -0,0 +1,7 @@
# my IoT services
This is show data from sensors around the house from Amazon DynamoDB.
It probably is dead or changes as time goes by.
Let's see.

66
router.go

@ -0,0 +1,66 @@
package main
// import (
// "fmt"
// "net/http"
// "github.com/gorilla/websocket"
// )
// type Message struct {
// Name string `json:"name"`
// Data interface{} `json:"data"`
// }
// type Client struct {
// send chan Message
// socket *websocket.Conn
// // findHandler FindHandler
// // session *r.Session
// }
// type Handler func(*Client, interface{})
// var upgrader = websocket.Upgrader{
// ReadBufferSize: 1024,
// WriteBufferSize: 1024,
// CheckOrigin: func(r *http.Request) bool { return true },
// }
// type Router struct {
// rules map[string]Handler
// // session *r.Session
// }
// func NewRouter() *Router {
// return &Router{
// rules: make(map[string]Handler),
// // session: session,
// }
// }
// func (r *Router) Handle(msgName string, handler Handler) {
// r.rules[msgName] = handler
// }
// func (r *Router) FindHandler(msgName string) (Handler, bool) {
// handler, found := r.rules[msgName]
// return handler, found
// }
// func (e *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// socket, err := upgrader.Upgrade(w, r, nil)
// if err != nil {
// w.WriteHeader(http.StatusInternalServerError)
// fmt.Fprint(w, err.Error())
// return
// }
// client := NewClient(socket, e.FindHandler, e.session)
// go client.Write()
// client.Read()
// }
// // func main() {
// // router := NewRouter()
// // // router.Handle('channel add', addChannel)
// // }
Loading…
Cancel
Save