-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.go
115 lines (102 loc) · 2.53 KB
/
gateway.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
// Gateway is a Lab "IoT" gateway server
package main
import (
"flag"
"fmt"
"github.com/FabLabBerlin/easylab-gw/endpoints"
"github.com/FabLabBerlin/easylab-gw/global"
"github.com/FabLabBerlin/easylab-gw/netswitches"
"gopkg.in/gcfg.v1"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
const UCI_PREFIX = "localmachines.@localmachines[0]"
func getUci(key string) (value string) {
cmd := exec.Command("/sbin/uci", "get", UCI_PREFIX+"."+key)
buf, err := cmd.CombinedOutput()
value = string(buf)
value = strings.TrimSpace(value)
if err != nil {
panic("get key '" + key + "': " + err.Error())
}
return
}
func ObtainServerJabberId() {
for {
jabberId, err := obtainServerJabberId()
if err == nil {
global.ServerJabberId = jabberId
break
} else {
log.Printf("error obtaining server jabber id: %v", err)
log.Printf("Retrying in 20 seconds...")
}
<-time.After(20 * time.Second)
}
}
func obtainServerJabberId() (jabberId string, err error) {
var resp *http.Response
resp, err = http.Get(*global.ServerPrefix + "/api/locations/jabber_connect")
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return "", fmt.Errorf("status code %v", resp.StatusCode)
}
var buf []byte
if buf, err = ioutil.ReadAll(resp.Body); err != nil {
return
}
jabberId = string(buf)
return
}
func main() {
global.ServerPrefix = flag.String("serverPrefix", "https://easylab.io", "")
uci := flag.Bool("uci", false, "use UCI")
flag.Parse()
if *uci {
var err error
global.Cfg.Main.LocationId, err = strconv.ParseInt(getUci("locationid"), 10, 64)
if err != nil {
panic("parse locationid: " + err.Error())
}
global.Cfg.XMPP.User = getUci("jabberid")
global.Cfg.XMPP.Pass = getUci("jabberpw")
tmp := strings.Split(global.Cfg.XMPP.User, "@")
if len(tmp) != 2 {
panic("expected jabberid to contain exactly one '@'")
}
global.Cfg.XMPP.Server = tmp[1] + ":5223"
global.DebugHttp("desired xmpp server='" + global.Cfg.XMPP.Server + "'")
} else {
err := gcfg.ReadFileInto(&global.Cfg, "conf/gateway.conf")
if err != nil {
log.Printf("gcfg read file into: %v", err)
}
}
ObtainServerJabberId()
netSwitches := netswitches.New()
chTerm := make(chan os.Signal, 1)
signal.Notify(chTerm, syscall.SIGINT, syscall.SIGTERM)
go func() {
for sig := range chTerm {
log.Printf("received signal %v", sig)
// sig is a ^C, handle it
os.Exit(1)
}
}()
go endpoints.NewXmpp(netSwitches)
// The gateway shall run forever..
for {
select {}
}
}