-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathloxone.go
1496 lines (1209 loc) · 36.1 KB
/
loxone.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package loxone
import (
"crypto/rsa"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/XciD/loxone-ws/crypto"
"github.com/XciD/loxone-ws/events"
"github.com/gorilla/websocket"
"github.com/hashicorp/go-version"
"github.com/lestrrat-go/jwx/jwt"
"github.com/mitchellh/mapstructure"
log "github.com/sirupsen/logrus"
)
const (
getApikey = "jdev/cfg/apiKey"
getPublicKey = "jdev/sys/getPublicKey"
keyExchange = "jdev/sys/keyexchange/%s"
getUsersalt = "jdev/sys/getkey2/%s"
getToken = "jdev/sys/gettoken/%s/%s/%d/%s/%s" // #nosec
getJwt = "jdev/sys/getjwt/%s/%s/%d/%s/%s" // #nosec
authWithToken = "authwithtoken/%s/%s" // #nosec
aesPayload = "salt/%s/%s"
aesPayloadNextSalt = "nextSalt/%s/%s/%s"
encryptionCmd = "jdev/sys/enc/%s"
encryptionCommandAndResponse = "jdev/sys/fenc/%s"
registerEvents = "jdev/sps/enablebinstatusupdate"
getConfig = "data/LoxAPP3.json"
MiniserverEpochOffset = 1230768000
)
// Body response form command sent by ws
type Body struct {
// Control name of the control invoked
Control string
// Code status
Code int32
}
// SimpleValue represent a simple Loxone Response Value
type SimpleValue struct {
// The value answered
Value string
}
// Config represent the LoxAPP3.json config file
type Config struct {
// LastModified
LastModified string
// MsInfo
MsInfo map[string]interface{}
// GlobalStates states about the sun, the day, etc
GlobalStates map[string]string
// OperatingModes of the loxone server
OperatingModes map[string]interface{}
// Rooms of the loxone server
Rooms map[string]*Room
// Cats Categories of the loxone server
Cats map[string]*Category
// Controls all the control of the loxone server
Controls map[string]*Control
}
func (cfg *Config) CatName(key interface{}) string {
k, ok := key.(string)
if !ok {
return ""
}
cat, ok := cfg.Cats[k]
if !ok {
return ""
}
return cat.Name
}
func (cfg *Config) RoomName(key interface{}) string {
k, ok := key.(string)
if !ok {
return ""
}
room, ok := cfg.Rooms[k]
if !ok {
return ""
}
return room.Name
}
// Control represent a control
type Control struct {
Name string
Type string
UUIDAction string
IsFavorite bool `json:"isFavorite"`
Room string
Cat string
States map[string]interface{} // Can be an array or a string
Details ControlDetails
Statistic ControlStatistic
SubControls map[string]*Control
}
// StatisticalNames returns a list of names for the given control and
// the statistical data the control writes. first we will loop over the
// outputs values within the statistics of the control, trying to find
// a state with a matching uuid. If no entry was found, we will use the
// name of the statistic entry in the output array.
func (cntl *Control) StatisticalNames() []string {
names := make([]string, 0)
// loop over the statistic outputs
for _, output := range cntl.Statistic.Outputs {
var name string
// loop over the states
for key, state := range cntl.States {
// now get the name of the state
// which matches and set it as name
if state == output.UUID {
name = key
break
}
}
// if the name wasn't found, use the
// name of the output from the statistic
if name == "" {
name = output.Name
}
// append the name
names = append(names, name)
}
return names
}
type ControlStatistic struct {
Frequency int `json:"frequency"`
Outputs []ControlStatisticItem `json:"outputs"`
}
type ControlStatisticItem struct {
ID int `json:"id"`
Name string `json:"name"`
Format string `json:"format"`
UUID string `json:"uuid"`
VisuType int `json:"visuType"`
}
// GetControl returns the control with the given uuid
func (cfg *Config) GetControl(uuid string) *Control {
for key, control := range cfg.Controls {
if key == uuid {
return control
}
}
return nil
}
// ControlDetails details of a control
type ControlDetails struct {
Format string
}
// Room represent a room
type Room struct {
Name string
UUID string
Type int32
}
// Category represent a category
type Category struct {
Name string
UUID string
Type string
}
// Loxone The loxone object exposed
type websocketImpl struct {
host string
port uint16
user string
password string
encrypt *encrypt
token *token
Events chan events.Event
callbackChannel chan *websocketResponse
socketMessage chan []byte
socket *websocket.Conn
connectedMu sync.RWMutex
isConnected bool
connectedHandler func(bool)
disconnected chan bool
safeStop sync.Once
stop chan bool
hooks map[string]func(events.Event)
registerEvents bool
autoReconnect bool
reconnectTimeout time.Duration
socketMu sync.Mutex
keepaliveInterval time.Duration
connectionTimeout time.Duration
miniserverMac string
useTLS bool
insecureSkipVerify bool
httpTransport *http.Transport
// Miniserver capabilities
httpsSupported uint8 // in jdev/cfg/apiKey response (httpsStatus: 1 Supported, 2 Supported but expired)
useJwt bool // 10.1.12.5
useSHA256 bool // 10.4.0.0
}
// we only support token auth so assume min version 9.0.7.25 for this library
/*
TOKEN_CFG_VERSION: "8.4.5.10",
ENCRYPTION_CFG_VERSION: "8.1.10.14",
TOKENS: "9.0.7.25",
NON_TOKEN_AUTH_SUPPORTED: "9.3.0.0",
ENCRYPTED_SOCKET_CONNECTION: "7.4.4.1",
ENCRYPTED_CONNECTION_FULLY: "8.1.10.14",
ENCRYPTED_CONNECTION_HTTP_USER: "8.1.10.4",
TOKEN_REFRESH_AND_CHECK: "10.0.9.13", // Tokens may now change when being refreshed. New webservice for checking token validity without changing them introduced
SECURE_HTTP_REQUESTS: "7.1.9.17",
JWT_SUPPORT: "10.1.12.5", // From this version onwards, JWTs are handled using separate commands to ensure regular apps remain unchanged.
SHA_256: "10.4.0.0"
*/
type LoxoneDownloadSocket interface {
Close()
Done() <-chan bool
IsConnected() bool
SetConnectedHandler(func(bool))
GetFile(filename string) ([]byte, error)
}
type Loxone interface {
GetEvents() <-chan events.Event
Done() <-chan bool
AddHook(uuid string, callback func(events.Event))
SendCommand(command string, class interface{}) (*Body, error)
SendEncryptedCommand(command string, class interface{}) (*Body, error)
GetDownloadSocket() (LoxoneDownloadSocket, error)
Close()
RegisterEvents() error
PumpEvents(stop <-chan bool)
GetConfig() (*Config, error)
IsConnected() bool
SetConnectedHandler(func(bool))
}
type websocketResponse struct {
data []byte
responseType events.EventType
}
type encrypt struct {
publicKey *rsa.PublicKey
key string
iv string
timestamp time.Time
salt string
}
type token struct {
Token string
Key string
ValidUntil int64
TokenRights int32
UnsecurePass bool
}
func (t *token) IsValid() bool {
epoch := t.ValidUntil + MiniserverEpochOffset - 30 // 30 second buffer before expiration
validTil := time.Unix(epoch, 0)
return time.Now().Before(validTil)
}
// HashAlg defines the algorithm used to hash some user
// information during token generation
type HashAlg string
const (
SHA1 HashAlg = "SHA1"
SHA256 HashAlg = "SHA256"
)
// Valid checks for valid & supported hash algorithms. The
// value for the algorithm is returned by the miniserver within
// the process of getting an auth-token and will be used for
// hashing {password}:{userSalt} and {user}:{pwHash} within
// createToken() / hashUser()
func (ha HashAlg) Valid() bool {
return (ha == SHA1 || ha == SHA256) && len(ha) > 0
}
type salt struct {
OneTimeSalt string `mapstructure:"key"`
Salt string `mapstructure:"Salt"`
HashAlgorithm HashAlg `mapstructure:"hashAlg"`
}
type encryptType int32
const (
none encryptType = 0
request encryptType = 1
requestResponseVal encryptType = 2
)
// WebsocketOption is a type we use to customise our websocket, it enables dynamic configuration in an easy to use API
type WebsocketOption func(*websocketImpl) error
// WithAutoReconnect allows you to disable auto reconnect behaviour by passing this option with 'false'
func WithAutoReconnect(autoReconnect bool) WebsocketOption {
return func(ws *websocketImpl) error {
ws.autoReconnect = autoReconnect
return nil
}
}
// WithKeepAliveInterval allows you to set the interval where keepalive messages are sent,
// a duration of 0 disables keepalive. If not specified it will default to 2 seconds as per Loxone's own LxCommunicator.
func WithKeepAliveInterval(keepAliveInterval time.Duration) WebsocketOption {
return func(ws *websocketImpl) error {
ws.keepaliveInterval = keepAliveInterval
return nil
}
}
// WithConnectionTimeout allows you to set the connection timeout, the connection will close if nothing is
// received for this amount of time.
// If keepalive is enabled this will default to 3 * keepaliveTimeout, otherwise the connection will not timeout
// unless this option is specified. If keepalive is enabled this value must be higher than keepaliveInterval.
func WithConnectionTimeout(connectionTimeout time.Duration) WebsocketOption {
return func(ws *websocketImpl) error {
ws.connectionTimeout = connectionTimeout
return nil
}
}
// WithReconnectTimeout sets the time between disconnection and reconnect attempts
func WithReconnectTimeout(timeout time.Duration) WebsocketOption {
return func(ws *websocketImpl) error {
ws.reconnectTimeout = timeout
return nil
}
}
// WithRegisterEvents automatically registers for events upon connecting to the Miniserver
func WithRegisterEvents() WebsocketOption {
return func(ws *websocketImpl) error {
ws.registerEvents = true
return nil
}
}
// WithURL allows initialising with a URL including schema, host and port e.g. http(s)://1.2.3.4:7494 or ws(s)://1.2.3.4:7494
func WithURL(urlString string) WebsocketOption {
return func(ws *websocketImpl) error {
u, err := url.Parse(urlString)
if err != nil {
return err
}
ws.updateFromURL(u)
return nil
}
}
// WithoutSSLVerification skips certificate verification to allow self-signed certificates or connections directly to an IP address
func WithoutSSLVerification() WebsocketOption {
return func(ws *websocketImpl) error {
ws.insecureSkipVerify = true
ws.httpTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
return nil
}
}
// WithHost connects using a given host name or ip address
func WithHost(host string) WebsocketOption {
return func(ws *websocketImpl) error {
ws.host = host
return nil
}
}
// WithCloudDNS will initiate the websocket to resolve the protocol, hostname and port from Loxone's Cloud DNS
func WithCloudDNS(miniserverMac string) WebsocketOption {
return func(ws *websocketImpl) error {
ws.miniserverMac = strings.ToLower(strings.ReplaceAll(miniserverMac, ":", ""))
return nil
}
}
// WithPort set a custom port for the Miniserver
func WithPort(port uint16) WebsocketOption {
return func(ws *websocketImpl) error {
ws.port = port
return nil
}
}
// WithUsernameAndPassword sets the username and password authentication, also used when supplied with a JWT
// to generate a new token if the provided token expires before being refreshed
func WithUsernameAndPassword(username string, password string) WebsocketOption {
return func(ws *websocketImpl) error {
if ws.user != "" && ws.user != username {
return errors.New("the username you specified in WithUsernameAndPassword() doesn't match that of the token you provided")
}
ws.user = username
ws.password = password
return nil
}
}
// WithJWTToken pre-sets the authentication token, at the moment there is no automatic refresh mechanism so it
// is safer to use alongside username and password authentication
func WithJWTToken(tokenString string) WebsocketOption {
return func(ws *websocketImpl) error {
jwtToken, err := jwt.Parse([]byte(tokenString))
if err != nil {
return err
}
loxoneToken := &token{
Token: tokenString,
}
exp := jwtToken.Expiration()
if !exp.IsZero() {
loxoneToken.ValidUntil = exp.Unix() - MiniserverEpochOffset
}
if rights, exists := jwtToken.Get("tokenRights"); exists {
if rightsInt, ok := rights.(int32); ok {
loxoneToken.TokenRights = rightsInt
}
}
if username, exists := jwtToken.Get("user"); exists {
if username, ok := username.(string); ok {
if ws.user != "" && ws.user != username {
return errors.New("the username you specified in WithUsernameAndPassword() doesn't match that of the token you provided")
}
ws.user = username
}
}
if ws.user == "" {
return errors.New("could not infer the user from the token")
}
ws.token = loxoneToken
return nil
}
}
func newBase() *websocketImpl {
return &websocketImpl{
port: 80,
Events: make(chan events.Event),
callbackChannel: make(chan *websocketResponse),
disconnected: make(chan bool, 1), // buffered in case reconnectHandler is already done (on close for example)
stop: make(chan bool),
hooks: make(map[string]func(events.Event)),
socketMessage: make(chan []byte),
useJwt: true,
useSHA256: true,
httpTransport: http.DefaultTransport.(*http.Transport).Clone(),
}
}
// New creates a websocket and connects to the Miniserver
func New(opts ...WebsocketOption) (Loxone, error) {
loxone := newBase()
// normal (non-download) socket defaults
loxone.autoReconnect = true
loxone.reconnectTimeout = 30 * time.Second
loxone.keepaliveInterval = 2 * time.Second
// Loop through each option
for _, opt := range opts {
err := opt(loxone)
if err != nil {
return nil, err
}
}
if loxone.keepaliveInterval > 0 && loxone.connectionTimeout == 0 {
loxone.connectionTimeout = 3 * loxone.keepaliveInterval
}
if loxone.connectionTimeout < loxone.keepaliveInterval {
return nil, errors.New("you cannot have a connection timeout less than the keepalive interval")
}
if loxone.token == nil && (loxone.user == "" || loxone.password == "") {
return nil, errors.New("you must specify at least one of WithUsernameAndPassword() or WithJWTToken() options")
}
if loxone.host == "" && loxone.miniserverMac == "" {
return nil, errors.New("you must specify at least one of WithURL(), WithHost() or WithCloudDNS()")
}
go loxone.handleMessages()
err := loxone.connect()
if err != nil {
close(loxone.stop) // need to stop any open goroutines
return nil, err
}
return loxone, nil
}
func (l *websocketImpl) IsConnected() bool {
l.connectedMu.RLock()
defer l.connectedMu.RUnlock()
return l.isConnected
}
func (l *websocketImpl) SetConnectedHandler(h func(bool)) {
l.connectedMu.Lock()
l.connectedHandler = h
l.connectedMu.Unlock()
}
// GetDownloadSocket clones the existing socket but without keepalive or timeout specifically to perform file downloads
func (l *websocketImpl) GetDownloadSocket() (LoxoneDownloadSocket, error) {
// clone current socket but with no keepalive or timeout
downloadSocket := newBase()
downloadSocket.host = l.host
downloadSocket.port = l.port
downloadSocket.useTLS = l.useTLS
downloadSocket.user = l.user
downloadSocket.password = l.password
downloadSocket.token = l.token
go downloadSocket.handleMessages()
err := downloadSocket.connect()
if err != nil {
return nil, err
}
return downloadSocket, nil
}
type cloudDnsResponse struct {
CMD string `json:"cmd"`
Code uint16
IP string
PortOpen bool
DNSStatus string `json:"DNS-Status"`
Datacenter string
IPHTTPS string
PortOpenHTTPS bool
}
func getPortString(hostComponents []string, https bool) string {
if len(hostComponents) > 1 {
return hostComponents[1]
} else if https {
return "443"
} else {
return "80"
}
}
// Url provides the url connection string based on a Cloud DNS response
func (cdr *cloudDnsResponse) Url(miniserverMac string) *url.URL {
var hostComponents []string
scheme := "ws"
var port string
if cdr.PortOpenHTTPS {
hostComponents = strings.Split(cdr.IPHTTPS, ":")
scheme = "wss"
port = getPortString(hostComponents, true)
} else if cdr.PortOpen {
hostComponents = strings.Split(cdr.IP, ":")
port = getPortString(hostComponents, false)
} else {
return nil
}
if cdr.Datacenter == "" {
cdr.Datacenter = "loxonecloud.com"
}
ipHost := strings.ReplaceAll(hostComponents[0], ".", "-")
return &url.URL{Scheme: scheme, Host: fmt.Sprintf("%s.%s.dyndns.%s:%s", ipHost, miniserverMac, cdr.Datacenter, port)}
}
func (l *websocketImpl) updateFromURL(u *url.URL) {
if u.Scheme == "wss" || u.Scheme == "https" {
l.useTLS = true
}
port, err := strconv.ParseUint(u.Port(), 10, 16)
if err != nil {
if l.useTLS {
port = 443
} else {
port = 80
}
}
l.host = u.Hostname()
l.port = uint16(port)
}
func (l *websocketImpl) resolveLoxoneDNS() error {
log.Info("Resolving connection details via Loxone Cloud DNS")
client := &http.Client{}
client.Timeout = 5 * time.Second
req, err := http.NewRequest("GET", fmt.Sprintf("https://dns.loxonecloud.com/?getip&snr=%s&json=true", l.miniserverMac), nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("loxone cloud dns request failed with code '%d'", resp.StatusCode)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
response := &cloudDnsResponse{}
err = json.Unmarshal(body, response)
if err != nil {
return err
}
u := response.Url(l.miniserverMac)
l.updateFromURL(u)
log.Infof("Resolved URL to be: %s", u.String())
return nil
}
func (l *websocketImpl) connect() error {
if l.host == "" && l.miniserverMac != "" {
err := l.resolveLoxoneDNS()
if err != nil {
return err
}
}
// this is recommended to be done first by docs, gives MS version and HTTPS status
log.Info("Asking for API Key, Version, and HTTPS Status ")
err := l.getMiniserverCapabilities()
if err != nil {
return err
}
err = l.connectWs()
if err != nil {
return err
}
err = l.authenticate()
if err != nil {
// if auth fails on a reconnect, there's no point in trying any more, assume password changed?
return err
}
l.setConnected(true)
if l.registerEvents {
// handle this error?
_ = l.RegisterEvents()
}
// Handle disconnected
go l.handleReconnect()
return nil
}
func (l *websocketImpl) handleReconnect() {
// If we finish, we restart a reconnect loop
// init a timer we may not need, but need the channel to be valid
keepAliveTimer := time.NewTimer(0)
<-keepAliveTimer.C
defer func() {
keepAliveTimer.Stop()
log.Info("Stopping disconnect loop")
}()
log.Info("Starting disconnect loop")
for {
if l.keepaliveInterval > 0 {
keepAliveTimer.Reset(l.keepaliveInterval)
}
select {
case <-l.stop:
return
case <-l.disconnected:
l.setConnected(false)
// if auto reconnect is disabled, close the stop channel and return immediately
if !l.autoReconnect {
close(l.stop)
return
}
for {
log.Warnf("Disconnected, reconnecting in %s", l.reconnectTimeout)
// check for stop during reconnect loop
select {
case <-l.stop:
return
case <-time.After(l.reconnectTimeout):
err := l.connect()
if err != nil {
log.Warnf("Error during reconnection, retrying (%s)", err.Error())
continue
}
return
}
}
case <-keepAliveTimer.C:
log.Trace("Sending keepalive")
_ = l.write(websocket.TextMessage, []byte("keepalive"))
}
}
}
func (l *websocketImpl) setConnected(connected bool) {
l.connectedMu.Lock()
l.isConnected = connected
if l.connectedHandler != nil {
l.connectedHandler(connected)
}
l.connectedMu.Unlock()
}
// Close closes the connection to the Miniserver
func (l *websocketImpl) Close() {
l.safeStop.Do(func() {
close(l.stop)
_ = l.write(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
_ = l.socket.Close()
})
}
func (l *websocketImpl) write(messageType int, data []byte) error {
// as per https://pkg.go.dev/github.com/gorilla/websocket#hdr-Concurrency ensuring one concurrent write
// another option is to set up a write pump, we can't assume user isn't using goroutines to issue commands
l.socketMu.Lock()
defer l.socketMu.Unlock()
return l.socket.WriteMessage(messageType, data)
}
// RegisterEvents ask the Miniserver to send events
func (l *websocketImpl) RegisterEvents() error {
l.registerEvents = true
_, err := l.SendCommand(registerEvents, nil)
if err != nil {
return err
}
return nil
}
// AddHook add a hook for a specific control, assumed at most one hook per uuid
func (l *websocketImpl) AddHook(uuid string, callback func(events.Event)) {
l.hooks[uuid] = callback
}
// GetEvents returns the events in a receive only channel
func (l *websocketImpl) GetEvents() <-chan events.Event {
return l.Events
}
// Done returns the stop channel to indicate the socket has been called to close
func (l *websocketImpl) Done() <-chan bool {
return l.stop
}
// PumpEvents starts processing events to trigger registered hooks
func (l *websocketImpl) PumpEvents(stop <-chan bool) {
go func() {
for {
select {
case <-stop:
log.Infof("Shutting Down")
return
case event := <-l.Events:
if hook, ok := l.hooks[event.UUID]; ok {
hook(event)
}
log.Debugf("event: %+v\n", event)
}
}
}()
}
// GetConfig get the Miniserver config
func (l *websocketImpl) GetConfig() (*Config, error) {
config := &Config{}
_, err := l.SendCommand(getConfig, config)
if err != nil {
return nil, err
}
return config, nil
}
// GetFile downloads a file with the specified filename
func (l *websocketImpl) GetFile(filename string) ([]byte, error) {
bytes := []byte(filename)
res, err := l.sendSocketCmd(&bytes)
if err != nil {
return nil, err
}
if res.responseType != events.EventTypeFile {
return nil, errors.New("request is not a binary file or it doesn't exist")
}
return res.data, nil
}
// SendCommand Send an unencrypted command to the Miniserver
func (l *websocketImpl) SendCommand(cmd string, class interface{}) (*Body, error) {
return l.sendCmdWithEnc(cmd, none, class)
}
// SendEncryptedCommand Send an encrypted command to the Miniserver
func (l *websocketImpl) SendEncryptedCommand(cmd string, class interface{}) (*Body, error) {
return l.sendCmdWithEnc(cmd, requestResponseVal, class)
}
func (l *websocketImpl) sendCmdWithEnc(cmd string, encryptType encryptType, class interface{}) (*Body, error) {
encryptedCmd, err := l.encrypt.getEncryptedCmd(cmd, encryptType)
if err != nil {
return nil, err
}
result, err := l.sendSocketCmd(&encryptedCmd)
if err != nil {
return nil, err
}
if encryptType == requestResponseVal {
// We need to decrypt
decryptedResult, err := l.encrypt.decryptCmd(result.data)
if err != nil {
return nil, err
}
result.data = decryptedResult
}
if class != nil {
if result.responseType == events.EventTypeText {
body, err := deserializeLoxoneResponse(result.data, class)
if err != nil {
return nil, err
}
if body.Code != 200 {
return nil, fmt.Errorf("error server, code: %d", body.Code)
}
return body, nil
} else if result.responseType == events.EventTypeFile {
err := json.Unmarshal(result.data, &class)
if err != nil {
return nil, err
}
// Response is copied to class
return nil, nil
}
return nil, fmt.Errorf("unHandled response type: %d", result.responseType)
}
log.Debug(string(result.data))
return &Body{Code: 200}, nil
}
func (l *websocketImpl) sendSocketCmd(cmd *[]byte) (*websocketResponse, error) {
log.Debug("Sending command to WS")
if err := l.write(websocket.TextMessage, *cmd); err != nil {
return nil, err
}
log.Debug("Waiting for answer")
result := <-l.callbackChannel
log.Debugf("WS answered")
return result, nil
}
func (l *websocketImpl) authenticate() error {
// Retrieve public key
log.Info("Asking for Public Key")
publicKey, err := l.getPublicKeyFromServer()
if err != nil {
return err
}
log.Info("Public Key OK")
// Create an unique key and an iv for AES
uniqueID := crypto.CreateEncryptKey(32)
ivKey := crypto.CreateEncryptKey(16)
// encrypt both and send them to server to get a Salt
cipherMessage, err := crypto.EncryptWithPublicKey([]byte(fmt.Sprintf("%s:%s", uniqueID, ivKey)), publicKey)
if err != nil {
return err
}
log.Info("Key Exchange with Miniserver")
resultValue := &SimpleValue{}
_, err = l.sendCmdWithEnc(fmt.Sprintf(keyExchange, cipherMessage), none, resultValue)
if err != nil {
return err
}
oneTimeSalt, err := crypto.DecryptAES(resultValue.Value, uniqueID, ivKey)
if err != nil {
return err
}
l.encrypt = &encrypt{
publicKey: publicKey,
key: uniqueID,
iv: ivKey,
timestamp: time.Now(),
salt: crypto.CreateEncryptKey(2),
}
log.Info("Key Exchange OK")
log.Info("Authentication Starting")