/
main.go
212 lines (175 loc) · 4.17 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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
//"wladmeixner.de/homeautomat/modules"
"github.com/boltdb/bolt"
color "github.com/fatih/color"
"github.com/gorilla/sessions"
)
// Create struct for settings
// TODO: move to some more usefull location
type Config struct {
Name string
Port string
HTMLPath string
Database string
}
// Global vars
var (
Debug bool
DummyMode bool
ConfigPath string
Conf = Config{}
// Construct better structure for DB (for testing purposes)
DB *bolt.DB
// Local vars
// Test for cookie session management (not ready)
store = sessions.NewCookieStore([]byte("something-very-secret"))
)
// Read in and parse the congig
// path: Path to config file
func initConf(path string) error {
// Load settings from conf.json
file, err := os.Open(path)
decoder := json.NewDecoder(file)
// Could not load config file.
if err != nil {
color.Red("ERROR:", err)
if path != "conf.json" {
fmt.Println("Looking in current directory")
initConf("./conf.json")
}
return err
}
// Handle parsing errors
err = decoder.Decode(&Conf)
if err != nil {
fmt.Println("error:", err.Error())
return err
}
if Debug {
color.Green("[SETTINGS: OK]")
fmt.Println("Settings Data:", Conf)
}
return nil
}
// Init basic strctures in the database
func initDatabase(dbPath string) (*bolt.DB, error) {
db, err := bolt.Open(dbPath, 0600, nil)
if err != nil {
return nil, err
}
color.Green("[DB: OK]")
// Init buckets if not present
for i := 0; i < 2; i++ {
err = db.Update(func(tx *bolt.Tx) error {
switch i {
// Init a bucket for the devices
case 0:
_, err := tx.CreateBucketIfNotExists([]byte("devices"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
// Init a bucket for the rooms
default:
_, err := tx.CreateBucketIfNotExists([]byte("rooms"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
}
})
}
if err != nil {
log.Fatal("Could not create bucket in DB", err)
}
return db, nil
}
// Prepare programm for equit.
// Close server, write data and close sockets.
func controlledQuit(c chan os.Signal) {
<-c
quit()
}
func quit() {
color.Green("Cleany closy worky worky...")
// Close database.
err := DB.Close()
if err != nil {
color.Red("Could not close DB ", err)
}
color.Yellow("Quiting programm")
// Exit programm
os.Exit(0)
}
// Reads in all command line arguments and
func main() {
// Asign flag
flag.BoolVar(&Debug, "debug", false, "Almost everything will be logged if this is true")
// Asign flag
flag.BoolVar(&DummyMode, "dummy", false, "Starts server in debug mode with dummy 433 MHz controller")
// Asign flag
flag.StringVar(&ConfigPath, "path", "conf.json", "Give path to the config pathr")
// Parse flags
flag.Parse()
// TEST FLAG values
if Debug {
color.Yellow("[SERVER RUNNING IN DEBUG MODE!!]")
}
if DummyMode {
color.Red("[SERVER RUNNING IN DUMMY MODE!]")
}
// Read config file
err := initConf(ConfigPath)
if err != nil {
color.Red("ERROR while parsing config file.", err.Error())
return
}
// Setup server quit action (^C)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go controlledQuit(c)
// Init bolt database
DB, err = initDatabase(Conf.Database)
if err != nil {
log.Fatal(err)
}
defer DB.Close()
// Init device types.
InitDeviceTypes()
// Init test RCCSimple Type
InitRCC()
// TODO: add one or more rooms
if Debug {
d := Device{0, "Power Toggle", "RCCSimple", 22}
deviceID, err := d.SaveToDB()
if err != nil {
color.Red("Failed to add new device to DB. This is kind of fatal so go panic, try not to cry, cry a lot!")
quit()
}
color.Green("Device added with id:", deviceID)
ListDevices()
err = RemoveFromDB("devices", deviceID)
if err != nil {
color.Red("Failed to remove device from DB. This is kind of fatal so go panic and cry!")
quit()
}
// Test GPIO
}
if !DummyMode {
color.Yellow("[TESTING GPIO!!]")
testGPIO()
testRCCSend()
}
// Create Router (multiplexer)
router := NewRouter()
color.Green("[SERVER RUNNING]")
log.Fatal(http.ListenAndServe(":"+Conf.Port, router))
}