This repository has been archived by the owner on Jan 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 124
/
main.go
230 lines (184 loc) · 5.2 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// IoT Wifi Management
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/bhoriuchi/go-bunyan/bunyan"
"github.com/cjimti/iotwifi/iotwifi"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
// ApiReturn structures a message for returned API calls.
type ApiReturn struct {
Status string `json:"status"`
Message string `json:"message"`
Payload interface{} `json:"payload"`
}
func main() {
logConfig := bunyan.Config{
Name: "iotwifi",
Stream: os.Stdout,
Level: bunyan.LogLevelDebug,
}
blog, err := bunyan.CreateLogger(logConfig)
if err != nil {
panic(err)
}
blog.Info("Starting IoT Wifi...")
messages := make(chan iotwifi.CmdMessage, 1)
cfgUrl := setEnvIfEmpty("IOTWIFI_CFG", "cfg/wificfg.json")
port := setEnvIfEmpty("IOTWIFI_PORT", "8080")
go iotwifi.RunWifi(blog, messages, cfgUrl)
wpacfg := iotwifi.NewWpaCfg(blog, cfgUrl)
apiPayloadReturn := func(w http.ResponseWriter, message string, payload interface{}) {
apiReturn := &ApiReturn{
Status: "OK",
Message: message,
Payload: payload,
}
ret, _ := json.Marshal(apiReturn)
w.Header().Set("Content-Type", "application/json")
w.Write(ret)
}
// marshallPost populates a struct with json in post body
marshallPost := func(w http.ResponseWriter, r *http.Request, v interface{}) {
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
blog.Error(err)
return
}
defer r.Body.Close()
decoder := json.NewDecoder(strings.NewReader(string(bytes)))
err = decoder.Decode(&v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
blog.Error(err)
return
}
}
// common error return from api
retError := func(w http.ResponseWriter, err error) {
apiReturn := &ApiReturn{
Status: "FAIL",
Message: err.Error(),
}
ret, _ := json.Marshal(apiReturn)
w.Header().Set("Content-Type", "application/json")
w.Write(ret)
}
// handle /status POSTs json in the form of iotwifi.WpaConnect
statusHandler := func(w http.ResponseWriter, r *http.Request) {
status, err := wpacfg.Status()
if err != nil {
blog.Error(err.Error())
return
}
apiPayloadReturn(w, "status", status)
}
// handle /connect POSTs json in the form of iotwifi.WpaConnect
connectHandler := func(w http.ResponseWriter, r *http.Request) {
var creds iotwifi.WpaCredentials
marshallPost(w, r, &creds)
blog.Info("Connect Handler Got: ssid:|%s| psk:|%s|", creds.Ssid, creds.Psk)
connection, err := wpacfg.ConnectNetwork(creds)
if err != nil {
blog.Error(err.Error())
return
}
apiReturn := &ApiReturn{
Status: "OK",
Message: "Connection",
Payload: connection,
}
ret, err := json.Marshal(apiReturn)
if err != nil {
retError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(ret)
}
// scan for wifi networks
scanHandler := func(w http.ResponseWriter, r *http.Request) {
blog.Info("Got Scan")
wpaNetworks, err := wpacfg.ScanNetworks()
if err != nil {
retError(w, err)
return
}
apiReturn := &ApiReturn{
Status: "OK",
Message: "Networks",
Payload: wpaNetworks,
}
ret, err := json.Marshal(apiReturn)
if err != nil {
retError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(ret)
}
// kill the application
killHandler := func(w http.ResponseWriter, r *http.Request) {
messages <- iotwifi.CmdMessage{Id: "kill"}
apiReturn := &ApiReturn{
Status: "OK",
Message: "Killing service.",
}
ret, err := json.Marshal(apiReturn)
if err != nil {
retError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(ret)
}
// common log middleware for api
logHandler := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
staticFields := make(map[string]interface{})
staticFields["remote"] = r.RemoteAddr
staticFields["method"] = r.Method
staticFields["url"] = r.RequestURI
blog.Info(staticFields, "HTTP")
next.ServeHTTP(w, r)
})
}
// setup router and middleware
r := mux.NewRouter()
r.Use(logHandler)
// set app routes
r.HandleFunc("/status", statusHandler)
r.HandleFunc("/connect", connectHandler).Methods("POST")
r.HandleFunc("/scan", scanHandler)
r.HandleFunc("/kill", killHandler)
http.Handle("/", r)
// CORS
headersOk := handlers.AllowedHeaders([]string{"Content-Type", "Authorization", "Content-Length", "X-Requested-With", "Accept", "Origin"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS", "DELETE"})
// serve http
blog.Info("HTTP Listening on " + port)
http.ListenAndServe(":"+port, handlers.CORS(originsOk, headersOk, methodsOk)(r))
}
// getEnv gets an environment variable or sets a default if
// one does not exist.
func getEnv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
// setEnvIfEmp<ty sets an environment variable to itself or
// fallback if empty.
func setEnvIfEmpty(env string, fallback string) (envVal string) {
envVal = getEnv(env, fallback)
os.Setenv(env, envVal)
return envVal
}