-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
291 lines (236 loc) · 5.69 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
package main
import (
"bufio"
"encoding/json"
"io/ioutil"
"fmt"
"log"
"net/http"
"os"
"regexp"
"time"
"github.com/boltdb/bolt"
"github.com/tarm/serial"
)
const dbname = "access.db"
var isOpen, isHLock bool = false, false
var serialPort *serial.Port
func main() {
config, err := readConfig()
if err != nil {
fmt.Printf("Error read config file %s", err.Error())
return
}
f, err := os.OpenFile(config.LogFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
log.SetOutput(f)
http.HandleFunc("/"+config.NormalModeEndpoint, webNormalMode)
http.HandleFunc("/"+config.HardLockModeEndpoint, webHLockMode)
http.HandleFunc("/"+config.CloseEndpoint, webCloseRelay)
http.HandleFunc("/"+config.OpenEndpoint, webOpenRelay)
http.HandleFunc("/"+config.AddKeyEndpoint, addKey)
http.HandleFunc("/"+config.ReadKeysEndpoint, readKeys)
http.HandleFunc("/"+config.DeleteKeyEndpoint, deleteKey)
go http.ListenAndServe(":"+config.HTTPPort, nil)
log.Printf("Listening on port %s...", config.HTTPPort)
db, err := bolt.Open(dbname, 0600, nil)
if err != nil {
log.Fatal(err)
}
db.Close()
c := &serial.Config{Name: config.SerialPort, Baud: 9600}
s, err := serial.OpenPort(c)
if err != nil {
fmt.Printf("Error open serial port %s ", err.Error())
log.Fatal(err)
}
serialPort = s
ch := make(chan bool) // wait chanel until key is valid
go getData(ch, s)
for {
time.Sleep(time.Second)
tmp := <-ch
if tmp {
if isOpen {
closeRelay()
} else {
openRelay()
}
}
}
}
func getData(ch chan bool, s *serial.Port) {
for {
reader := bufio.NewReader(s)
reply, err := reader.ReadBytes('\n')
if err != nil {
log.Fatal(err)
}
k := string(reply)
if chk := checkKey(k); chk {
ch <- chk
time.Sleep(2 * time.Second)
}
}
}
func invertBool() {
isOpen = !isOpen
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func boltStore(value Key) {
db, err := bolt.Open(dbname, 0600, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("keys"))
if err != nil {
return err
}
return b.Put([]byte(value.Key), []byte(value.isEnable))
})
}
func boltRead(key string) bool {
var strKey string
db, err := bolt.Open(dbname, 0600, nil)
if err != nil {
log.Fatal(err)
return false
}
defer db.Close()
db.View(func(tx *bolt.Tx) error {
re := regexp.MustCompile(`\r\n`)
key := re.ReplaceAllString(key, "")
re = regexp.MustCompile(`\n`)
key = re.ReplaceAllString(key, "")
re = regexp.MustCompile(`\r`)
key = re.ReplaceAllString(key, "")
log.Printf("Readed key: %s\n", key)
b := tx.Bucket([]byte("keys"))
v := b.Get([]byte(key))
strKey = string(v)
return nil
})
if strKey == "1" {
log.Printf("Key %s is valid\n", key)
return true
}
return false
}
func addKey(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
var key Key
key.Key = params.Get("key")
key.isEnable = params.Get("enable")
boltStore(key)
log.Printf("You add the key %s", key.Key)
fmt.Fprintln(w, "You add the key", key.Key)
}
func readKeys(w http.ResponseWriter, r *http.Request) {
keys := make(map[string]string)
db, err := bolt.Open(dbname, 0600, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("keys"))
b.ForEach(func(k, v []byte) error {
keys[string(k)] = string(v)
fmt.Printf("map: %s\n", keys[string(k)])
return nil
})
return nil
})
data, _ := json.Marshal(keys)
fmt.Fprintln(w, string(data))
}
func deleteKey(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
deleteKey := params.Get("key")
db, err := bolt.Open(dbname, 0600, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.Update(func(tx *bolt.Tx) error {
// Retrieve the users bucket.
// This should be created when the DB is first opened.
b := tx.Bucket([]byte("keys"))
err := b.Delete([]byte(deleteKey))
if err != nil {
fmt.Printf("Key: \"%s\" delete failed: %s\n", deleteKey, err.Error())
return err
}
fmt.Fprintf(w, "Key: \"%s\" deleted succesfully\n", deleteKey)
// Persist bytes to users bucket.
return nil
})
}
func webNormalMode(w http.ResponseWriter, r *http.Request) {
isHLock = false
_, err := serialPort.Write([]byte("hlock0"))
if err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "Normal Mode")
}
func webHLockMode(w http.ResponseWriter, r *http.Request) {
_, err := serialPort.Write([]byte("hlock1"))
if err != nil {
log.Fatal(err)
}
isHLock = true
fmt.Fprintln(w, "HardLock Mode")
}
func webCloseRelay(w http.ResponseWriter, r *http.Request) {
switchRelay()
fmt.Fprintln(w, "switch relay")
}
func webOpenRelay(w http.ResponseWriter, r *http.Request) {
openRelay()
fmt.Fprintln(w, "open lock")
}
func closeRelay() {
_, err := serialPort.Write([]byte("close"))
if err != nil {
log.Fatal(err)
}
invertBool()
log.Println("Close")
}
func openRelay() {
_, err := serialPort.Write([]byte("open"))
if err != nil {
log.Fatal(err)
}
invertBool()
log.Println("Open")
}
func switchRelay() {
if isOpen {
closeRelay()
} else {
openRelay()
}
}
func checkKey(key string) bool {
if boltRead(key) {
return true
}
return false
}
func readConfig() (*Config, error) {
plan, _ := ioutil.ReadFile("config.json")
config := Config{}
err := json.Unmarshal([]byte(plan), &config)
return &config, err
}