summaryrefslogtreecommitdiff
path: root/tools/websocket.go
blob: 594cb1b8dfa4b2eb0462f0a3d8e81083c323d248 (plain)
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
// Websocket debug tool
//
// Usage: ./websocket-linux-amd64 ws://<shelly-ip>/rpc
//
// This tools is intended to support development of the Websocket-based
// application programming interface (API) of the Shelly Internet of Things
// (IoT) devices.

package main

import (
	"encoding/json"
	"log"
	"net/url"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/gorilla/websocket"
)

func main() {
	log.SetFlags(0)

	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	var u url.URL = getURL()
	log.Printf("connecting to %s", u.String())

	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	go rx(c)

	getConfig(c)

	Await(syscall.SIGTERM, syscall.SIGINT)
}

func getURL() url.URL {
	if len(os.Args) != 2 {
		log.Fatalf("Exactly one argument expected but got %d.", len(os.Args) - 1)
	}

	maybeURL, err := url.Parse(os.Args[1])
	if err != nil {
		log.Fatalf("Cannot parse given URL: %s", os.Args[1])
	}

	return *maybeURL
}

func Await(signals ...os.Signal) {
	listener := make(chan os.Signal, 1)
	signal.Notify(listener, signals...)
	defer signal.Stop(listener)

	sig := <-listener
	log.Printf("Received OS signal '%v'\n", sig)
}

func getConfig(c *websocket.Conn) {
	request := `
{
	"jsonrpc":"2.0",
	"id": 1,
	"src":"user_1",
	"method":"Sys.GetConfig",
	"params": {
		"id":2
	}
}
`

	tx(c, request)
}

func rx(c *websocket.Conn) {
	for {
		_, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			return
		}
		log.Println("")
		log.Println(quote(prettify(string(message)), "< "))
	}
}

func tx(c *websocket.Conn, d string) {
	log.Println(quote(prettify(d), "> "))

	err := c.WriteMessage(websocket.TextMessage, []byte(d))
	if err != nil {
		log.Fatal(err)
	}
}

func prettify(input string) string {
	var parsed any

	err := json.Unmarshal([]byte(input), &parsed)
	if err != nil {
		log.Fatal(err)
	}

	pretty, err := json.MarshalIndent(parsed, "", "    ")
	if err != nil {
		log.Fatal(err)
	}

	return string(pretty)
}

func quote(input string, quotation string) string {
	lines := strings.Split(input, "\n")

	for i, line := range lines {
		lines[i] = quotation + line
	}

	return strings.Join(lines, "\n")
}