-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
280 lines (227 loc) · 8.26 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
// Error to be reported to the user
type Error struct {
Name string `json:"errorName"`
Desciption string `json:"errorDescription"`
}
// Hint to be shown to the user.
type Hint struct {
Icon string `json:"icon"`
Headline string `json:"headline"`
Description string `json:"description"`
}
// Challange can be masterd by the user to prove he is capable of saving energy.
type Challange struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Total int `json:"total"`
Succeeded int `json:"succeeded"`
}
// UserProfile with basic informationa about the current user.
type UserProfile struct {
Nick string `form:"nick" json:"nick"`
FlatSize float64 `form:"flatsize" json:"faltSize"`
FlatPopulation int `form:"flatpopulation" json:"flatPopulation"`
}
// HitlistEntry represents one entry int the hitlist.
type HitlistEntry struct {
Nick string `json:"nick"`
Position int `json:"position"`
Value string `json:"value"`
}
// LiveChartConsumer represents a consumer.
type LiveChartConsumer struct {
Icon string `json:"icon"`
Title string `json:"title"`
}
// LiveChartEntry represents an entry in the production/consumption chart.
type LiveChartEntry struct {
Date time.Time `json:"date"`
UserConsumption int `json:"userConsumption"`
GroupConsumtion int `json:"groupConsumption"`
GroupProduction int `json:"groupProduction"`
SelfSufficiency int `json:"selfSufficiency"`
UserConsumers []LiveChartConsumer `json:"userConsumers"`
groupConsumers []LiveChartConsumer `json:"groupConsumers"`
}
// MaxValuesHistory tells how many history values can be requested at once
const MaxValuesHistory = 10000
// PasswordMinLength specifies the minimum length of a user's password
const PasswordMinLength = 8
func main() {
var challangeRunning Challange
currentUser := UserProfile{"DarkNight", 120.0, 2}
hints := [3]Hint{
Hint{"HAIR_DRYER", "Don't dry your hair hot!", "Heating the air consumes a lot of energy. Besides, it is way better for your hair to dry it cold, belive me ;)"},
Hint{"PLUG", "Turn of your plugs.", "Devices in stand-by still consume energy. Turning the plug off will save you a log of energy."},
Hint{"CLOTHES_DRYER", "Dont't use a clothes dryer.", "These devices consume the most energy in your household. Besides your trousers will life longer when they dry on fresh air."}}
challanges := [3]Challange{
Challange{0, "Quiet thorught the nights", "Can you consume less than 1kwh 5 nights in a row?", 0, 0},
Challange{1, "Take it easy", "Can you consume less than 20 kwh for one week?", 0, 0},
Challange{2, "Beat youre self", "Consume less than in tha last week.", 0, 0}}
hitlist := [6]HitlistEntry{
HitlistEntry{"Lisl", 1, "1000kW"},
HitlistEntry{"Dieter", 2, "1300kW"},
HitlistEntry{"Heinz", 3, "1400kW"},
HitlistEntry{"Gunigunde", 4, "1700kW"},
HitlistEntry{"Sylvia Maria Eva", 5, "2000kW"},
HitlistEntry{"Y", 6, "2400kW"}}
route := gin.Default()
route.GET("/hints", func(c *gin.Context) {
c.JSON(200, hints)
})
route.GET("/challanges", func(c *gin.Context) {
c.JSON(200, challanges)
})
route.GET("/challanges/start/:id", func(c *gin.Context) {
idString := c.Param("id")
id, error := strconv.Atoi(idString)
if error != nil {
c.JSON(200, Error{"Unknown id", idString + " is not a known challange."})
return
}
if id >= len(challanges) {
c.JSON(200, Error{"Unknown id", idString + " is not a known challange."})
return
}
challangeRunning = challanges[id]
c.JSON(200, challangeRunning)
})
route.GET("/challanges/status", func(c *gin.Context) {
c.JSON(200, challangeRunning)
})
route.GET("/individual-consumption-history/begin/:begin/end/:end/tics/:tics", func(c *gin.Context) {
beginDateString := c.Param("begin")
endDateString := c.Param("end")
ticsString := c.Param("tics")
beginDate, error := time.Parse(time.RFC3339, beginDateString)
if error != nil {
c.JSON(200, Error{"Invalid begin date", beginDateString + " is not a valid RFC3339 date "})
return
}
endDate, error := time.Parse(time.RFC3339, endDateString)
if error != nil {
c.JSON(200, Error{"Invalid end date", endDateString + " is not a valid RFC3339 date "})
return
}
tics, error := strconv.Atoi(ticsString)
if error != nil {
c.JSON(200, Error{"Invalid values for tics ", ticsString + " is not a valid integer."})
return
}
if beginDate.After(endDate) {
c.JSON(200, Error{"Invalid values for dates ", "End date must be after begin date."})
return
}
totalValues := endDate.Sub(beginDate).Seconds() / float64(tics)
if totalValues > MaxValuesHistory {
c.JSON(200, Error{"Too many values requested ", "Max tics allowed: " + string(MaxValuesHistory)})
return
}
results := make([]float64, int(totalValues))
last := float64(0)
for i := 0; i < int(totalValues); i++ {
last += rand.Float64() * 10
results[i] = last
}
c.JSON(200, results)
})
route.GET("/group-consumption-history/begin/:begin/end/:end/tics/:tics", func(c *gin.Context) {
beginDateString := c.Param("begin")
endDateString := c.Param("end")
ticsString := c.Param("tics")
beginDate, error := time.Parse(time.RFC3339, beginDateString)
if error != nil {
c.JSON(200, Error{"Invalid begin date", beginDateString + " is not a valid RFC3339 date "})
return
}
endDate, error := time.Parse(time.RFC3339, endDateString)
if error != nil {
c.JSON(200, Error{"Invalid end date", endDateString + " is not a valid RFC3339 date "})
return
}
tics, error := strconv.Atoi(ticsString)
if error != nil {
c.JSON(200, Error{"Invalid values for tics ", ticsString + " is not a valid integer."})
return
}
if beginDate.After(endDate) {
c.JSON(200, Error{"Invalid values for dates ", "End date must be after begin date."})
return
}
totalValues := endDate.Sub(beginDate).Seconds() / float64(tics)
if totalValues > MaxValuesHistory {
c.JSON(200, Error{"Too many values requested ", "Max tics allowed: " + string(MaxValuesHistory)})
return
}
results := make([]float64, int(totalValues))
last := float64(0)
for i := 0; i < int(totalValues); i++ {
last += rand.Float64() * 100
results[i] = last
}
c.JSON(200, results)
})
route.GET("/profile", func(c *gin.Context) {
c.JSON(200, currentUser)
})
route.POST("/profile", func(c *gin.Context) {
if err := c.ShouldBindJSON(¤tUser); err != nil {
c.JSON(400, Error{"Can not parse profile.", "Maybe there are missing values?"})
return
}
c.JSON(200, currentUser)
})
route.GET("/hitlist", func(c *gin.Context) {
c.JSON(200, hitlist)
})
route.POST("/password", func(c *gin.Context) {
newPassword := c.PostForm("password")
token := c.PostForm("token")
if token != "expected" {
c.JSON(400, Error{"Unknown token", "Try again with a valid token."})
return
}
if len(newPassword) < PasswordMinLength {
c.JSON(400, Error{"Password too short", "Try again with a password at least " + strconv.Itoa(PasswordMinLength) + " chars long."})
return
}
c.JSON(200, gin.H{})
})
route.POST("/update-password", func(c *gin.Context) {
newPassword := c.PostForm("password")
if len(newPassword) < PasswordMinLength {
c.JSON(400, Error{"Password too short", "Try again with a password at least " + strconv.Itoa(PasswordMinLength) + " chars long."})
return
}
c.JSON(200, gin.H{})
})
route.GET("/live", func(c *gin.Context) {
var wsupgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := wsupgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
fmt.Println("Failed to create websocket")
return
}
users := []LiveChartConsumer{LiveChartConsumer{"i1", "Consumer one"}, LiveChartConsumer{"i2", "Consumer one"}}
e := LiveChartEntry{time.Now(), rand.Int() % 10, rand.Int() % 100, rand.Int() % 10, rand.Int() % 100, users, users}
for {
e = LiveChartEntry{time.Now(), e.UserConsumption + rand.Int()%10, e.GroupConsumtion + rand.Int()%100, e.GroupProduction + rand.Int()%100, rand.Int() % 100, users, users}
conn.WriteJSON(e)
time.Sleep(1000000000)
}
})
route.Run(":8088")
}