-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
105 lines (91 loc) · 2.46 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
package main
import (
"embed"
"flag"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/enbility/devices-app/app"
"github.com/gorilla/websocket"
)
//go:embed dist
var web embed.FS
const (
httpdPort int = 7050
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
// allow connection from any host
return true
},
}
func serveWs(cem *app.Cem, w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("upgrade error:", err)
return
}
conn := app.NewConnection(cem, ws)
cem.AddConnection(conn)
}
func usage() {
fmt.Println("General Usage:")
fmt.Println(" devices-app <httpd-port> <eebus-port> <crtfile> <keyfile> <serial>")
fmt.Println(" <httpd-port> Optional port for the HTTPD server")
fmt.Println(" <eebus-port> Optional port for the EEBUS service")
fmt.Println(" <crt-file> Optional filepath for the cert file")
fmt.Println(" <key-file> Option filepath for the key file")
fmt.Println(" <serial> Option mDNS serial string")
fmt.Println()
fmt.Println("Default values:")
fmt.Println(" httpd-port:", httpdPort)
fmt.Println(" eebus-port: 4815")
fmt.Println(" crt-file: cert.crt (same folder as executable)")
fmt.Println(" key-file: cert.key (same folder as executable)")
fmt.Println(" serial: 123456789")
fmt.Println()
fmt.Println("If no cert-file or key-file parameters are provided and")
fmt.Println("the files do not exist, they will be created automatically.")
}
func main() {
if len(os.Args) == 2 && os.Args[1] == "-h" {
usage()
return
}
portHttpd := httpdPort
if len(os.Args) > 1 {
if tempPort, err := strconv.Atoi(os.Args[1]); err == nil {
portHttpd = tempPort
}
}
log.Println("Web Server running at port", portHttpd)
hems := app.NewHems()
hems.Run()
serverRoot, err := fs.Sub(web, "dist")
if err != nil {
log.Fatal(err)
}
http.Handle("/", http.FileServer(http.FS(serverRoot)))
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
serveWs(hems, w, r)
})
go func() {
host := fmt.Sprintf("0.0.0.0:%d", portHttpd)
addr := flag.String("addr", host, "http service address")
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal(err)
}
}()
// Clean exit to make sure mdns shutdown is invoked
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
<-sig
// User exit
}