-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
351 lines (291 loc) · 8.68 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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package main
import (
"encoding/json"
"errors"
"math/rand"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
auth "github.com/abbot/go-http-auth"
"github.com/huin/goserial"
"golang.org/x/crypto/bcrypt"
)
type Artwork struct {
Name string
TL []bool
InRandom bool
}
type Settings struct {
Artworks []Artwork
// default mode will be 'random' which will randomly show artworks where
// InRandom is true. Other values might be 'time' which will show the time
// and 'countdown' for NYE.
Mode string
TimeDisplayTime int // how many seconds the current time is shown during random
RandomDisplayTime int // how many seconds the random artwork is shown
}
type Config struct {
ArtworksFile string
}
var (
WarningLogger *log.Logger
ErrorLogger *log.Logger
InfoLogger *log.Logger
CFM Settings
DATA_FILE string
Serial io.ReadWriteCloser
)
func init() {
file, err := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Println("can not create log file")
}
InfoLogger = log.New(file, "[I] ", log.Ldate|log.Ltime|log.Lshortfile)
WarningLogger = log.New(file, "[W] ", log.Ldate|log.Ltime|log.Lshortfile)
ErrorLogger = log.New(file, "[E] ", log.Ldate|log.Ltime|log.Lshortfile)
InfoLogger.Println("===============================================")
InfoLogger.Println("Server started")
const DATA_FILE = "./artworks.json"
loadArtworks(DATA_FILE)
arduinoPath, err := FindArduinoDevice()
if err != nil {
fmt.Println("Can't find Arduino!")
}
serialConfig := &goserial.Config{Name: arduinoPath, Baud: 9600}
Serial, err = goserial.OpenPort(serialConfig)
if err != nil {
fmt.Printf("Serial port not opening: %v\n", err)
return;
}
// needed for establishing the serial connection
time.Sleep(2 * time.Second)
CFMToBytes()
startLoop()
}
/******************************************************************************
ARDUINO PART
*******************************************************************************/
var quit chan struct{}
func sendRandomArtwork(artworks []Artwork) {
var message strings.Builder
randomIndex := rand.Intn(len(artworks))
for _, mode := range artworks[randomIndex].TL {
if mode {
message.WriteString("1")
} else {
message.WriteString("0")
}
}
Serial.Write([]byte(message.String()))
}
func startLoop() {
quit = make(chan struct{})
go loop()
}
func stopLoop() {
quit <- struct{}{}
}
func loop() {
// This ticker will put something in its channel every 2s
ticker := time.NewTicker(2 * time.Second)
// If you don't stop it, the ticker will cause memory leaks
defer ticker.Stop()
artworksInRandom := []Artwork{}
for i, artwork := range CFM.Artworks {
if artwork.InRandom {
artworksInRandom = append(artworksInRandom, CFM.Artworks[i])
}
}
for {
select {
case <-quit:
return
case <-ticker.C:
sendRandomArtwork(artworksInRandom)
}
}
}
func FindArduinoDevice() (string, error) {
contents, _ := ioutil.ReadDir("/dev")
for _, f := range contents {
if strings.Contains(f.Name(), "tty.usb") ||
strings.Contains(f.Name(), "ttyACM") ||
strings.Contains(f.Name(), "ttyUSB") {
InfoLogger.Println("Arduino found: /dev/" + f.Name())
return "/dev/" + f.Name(), nil
}
}
ErrorLogger.Println("can't find Arduino device in /dev/")
return "", errors.New("can't find Arduino device in /dev/")
}
func CFMToBytes() []byte {
var message strings.Builder
artworksInRandom := []Artwork{}
for i, artwork := range CFM.Artworks {
if artwork.InRandom {
artworksInRandom = append(artworksInRandom, CFM.Artworks[i])
}
}
randoms := len(artworksInRandom)
// config line
s := fmt.Sprintf("%s|%d|%d|%d|", CFM.Mode, CFM.TimeDisplayTime, CFM.RandomDisplayTime, randoms)
message.WriteString(s)
for i, artwork := range artworksInRandom {
num := int64(0)
for i, tl := range artwork.TL {
if tl {
num |= 1 << (i)
}
}
message.WriteString(fmt.Sprintf("%d", num))
if i != randoms-1 {
message.WriteString("|")
}
}
return []byte(message.String())
}
/******************************************************************************
WEBSERVER PART
*******************************************************************************/
func Secret(user, _ string) string {
if user == "jord" {
content, _ := ioutil.ReadFile("passwd.txt")
pw := strings.Split(string(content), "\n")[0]
return pw
}
return ""
}
func homePage(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
tmpl := template.Must(template.ParseFiles("templates/select.tmpl"))
if r.Method != http.MethodPost {
tmpl.Execute(w, CFM)
return
}
// TODO: do something with new value
val := r.FormValue("settings")
CFM.Mode = val
InfoLogger.Printf("New mode selected: %s\n", val)
tmpl.Execute(w, CFM)
}
func createPage(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
tmpl := template.Must(template.ParseFiles("templates/create.tmpl"))
if r.Method != http.MethodPost {
tmpl.Execute(w, CFM)
return
}
// TODO: do something with new value
val := r.FormValue("settings")
CFM.Mode = val
InfoLogger.Printf("New mode selected: %s\n", val)
tmpl.Execute(w, CFM)
}
func logPage(w http.ResponseWriter, _ *auth.AuthenticatedRequest) {
tmpl := template.Must(template.ParseFiles("templates/log.tmpl"))
content, err := ioutil.ReadFile("logs.txt")
if err != nil {
ErrorLogger.Println("can not read log file")
}
strParts := strings.Split(string(content), "\n")
tmpl.Execute(w, strParts)
}
func setPasswordPage(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
tmpl := template.Must(template.ParseFiles("templates/setpw.tmpl"))
if r.Method != http.MethodPost {
tmpl.Execute(w, nil)
return
}
newPw := r.FormValue("password")
InfoLogger.Println(newPw)
hashedPassword, hashErr := bcrypt.GenerateFromPassword([]byte(newPw), bcrypt.DefaultCost)
file, fileErr := os.OpenFile("passwd.txt", os.O_CREATE|os.O_WRONLY, 0666)
file.Truncate(0)
if hashErr != nil || fileErr != nil {
ErrorLogger.Println("not able to get password, run scripts/newpassword.go")
}
file.WriteString(string(hashedPassword))
defer file.Close()
tmpl.Execute(w, nil)
}
func receiveNewArtwork(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
w.WriteHeader(403)
w.Write([]byte("403 Forbidden"))
return
}
var art Artwork
err := json.NewDecoder(r.Body).Decode(&art)
if err != nil {
WarningLogger.Printf("JSON decode error: %s\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
InfoLogger.Printf("Received new artwork: %s\n", art.Name)
CFM.Artworks = append(CFM.Artworks, art)
// ensures that the arduino is updated
stopLoop()
startLoop()
writeArtworks(DATA_FILE)
}
func receiveAllArtworks(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
w.WriteHeader(403)
w.Write([]byte("403 Forbidden"))
return
}
err := json.NewDecoder(r.Body).Decode(&CFM.Artworks)
// ensures that the arduino is updated
stopLoop()
startLoop()
if err != nil {
WarningLogger.Printf("JSON decode error: %s\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
InfoLogger.Println("Received all artworks")
writeArtworks(DATA_FILE)
}
func writeArtworks(filepath string) {
jsonString, err := json.Marshal(&CFM)
if err != nil {
WarningLogger.Printf("json.Marshal error: %s\n", err)
return
}
ioutil.WriteFile(filepath, jsonString, 0644)
InfoLogger.Println("wrote new data to JSON file")
}
func loadArtworks(filepath string) {
// load artworks from file, happens at initalization
fileContent, err := ioutil.ReadFile(filepath)
if err != nil {
ErrorLogger.Printf("Not able to read artworks JSON: %s\n", err)
panic("Not able to read artworks JSON")
}
err = json.Unmarshal(fileContent, &CFM)
if err != nil {
ErrorLogger.Printf("json.Unmarshal error: %s\n", err)
panic("error parsing artworks JSON")
}
InfoLogger.Println("succesfully loaded in artworks from JSON")
}
func showCountdown(w http.ResponseWriter, r *http.Request) {
println("hi")
}
func main() {
authenticator := auth.NewBasicAuthenticator("example.com", Secret)
// static public files
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./public/js"))))
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./public/css"))))
http.Handle("/img/", http.StripPrefix("/img/", http.FileServer(http.Dir("./public/img"))))
http.HandleFunc("/", authenticator.Wrap(homePage))
http.HandleFunc("/create", authenticator.Wrap(createPage))
http.HandleFunc("/log", authenticator.Wrap(logPage))
http.HandleFunc("/setpw", authenticator.Wrap(setPasswordPage))
http.HandleFunc("/ajax", receiveNewArtwork)
http.HandleFunc("/ajax2", receiveAllArtworks)
http.HandleFunc("/countdown", showCountdown)
http.ListenAndServe(":4567", nil)
}