Added default CTRL+C signal handler.
[src/xds/xds-cli.git] / iosocket-client.go
1 /*
2  * Copyright (C) 2018 "IoT.bzh"
3  * Author Sebastien Douheret <sebastien@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 package main
20
21 import (
22         "fmt"
23         "sync"
24
25         socketio_client "github.com/sebd71/go-socket.io-client"
26 )
27
28 // IOSockClient .
29 type IOSockClient struct {
30         URL        string
31         Conn       *socketio_client.Client
32         Options    *socketio_client.Options
33         EmitMutex  *sync.Mutex
34         Connected  bool
35         EscapeKeys []byte
36 }
37
38 // NewIoSocketClient Create a new IOSockClient
39 func NewIoSocketClient(url, clientID string) (*IOSockClient, error) {
40
41         var err error
42
43         sCli := &IOSockClient{
44                 URL:       url,
45                 EmitMutex: &sync.Mutex{},
46                 Options: &socketio_client.Options{
47                         Transport: "websocket",
48                         Header:    make(map[string][]string),
49                 },
50         }
51         sCli.Options.Header["XDS-AGENT-SID"] = []string{clientID}
52
53         sCli.Conn, err = socketio_client.NewClient(url, sCli.Options)
54         if err != nil {
55                 return nil, fmt.Errorf("IO.socket connection error: " + err.Error())
56         }
57
58         sCli.Conn.On("connection", func() {
59                 sCli.Connected = true
60         })
61
62         sCli.Conn.On("disconnection", func(err error) {
63                 Log.Debugf("WS disconnection event with err: %v\n", err)
64                 sCli.Connected = false
65         })
66
67         return sCli, nil
68 }
69
70 // On record a callback on a specific message
71 func (c *IOSockClient) On(message string, f interface{}) (err error) {
72         return c.Conn.On(message, f)
73 }
74
75 // Emit send a message
76 func (c *IOSockClient) Emit(message string, args ...interface{}) (err error) {
77         c.EmitMutex.Lock()
78         defer c.EmitMutex.Unlock()
79         return c.Conn.Emit(message, args...)
80 }